text
stringlengths 24
5.1k
|
---|
this section: clearcurrenttoken() removes the current token. getblobvalue() returns the current token as a blob value. getbooleanvalue() returns the current token as a boolean value. getcurrentname() returns the name associated with the current token. getcurrenttoken() returns the token that the parser currently points to or null if there's no current token. getdatetimevalue() returns the current token as a date and time value. 3094apex reference guide jsonparser class getdatevalue() returns the current token as a date value. getdecimalvalue() returns the current token as a decimal value. getdoublevalue() returns the current token as a double value. getidvalue() returns the current token as an id value. getintegervalue() returns the current token as an integer value. getlastclearedtoken() returns the last token that was cleared by the clearcurrenttoken method. getlongvalue() returns the current token as a long value. gettext() returns the textual representation of the current token or null if there's no current token. gettimevalue() returns the current token as a time value. hascurrenttoken() returns true if the parser currently points to a token; otherwise, returns false. nexttoken() returns the next token or null if the parser has reached the end of the input stream. nextvalue() returns the next token that is a value type or null if the parser has reached the end of the input stream. readvalueas(apextype) deserializes json content into an object of the specified apex type and returns the deserialized object. readvalueasstrict(apextype) deserializes json content into an object of the specified apex type and returns the deserialized object. all attributes in the json content must be present in the specified type. skipchildren() skips all child tokens of type jsontoken.start_array and jsontoken.start_object that the parser currently points to. clearcurrenttoken() removes the current token. signature public void clearcurrenttoken() 3095apex reference guide jsonparser class return value type: void usage after this method is called, a call to hascurrenttoken returns false and a call to getcurrenttoken returns null. you can retrieve the cleared token by calling getlastclearedtoken. getblobvalue() returns the current token as a blob value. signature public blob getblobvalue() return value type: blob usage the current token must be of type jsontoken.value_string and must be base64-encoded. getbooleanvalue() returns the current token as a boolean value. signature public boolean getbooleanvalue() return value type: boolean usage the current token must be of type jsontoken.value_true or jsontoken.value_false. the following example parses a sample json string and retrieves a boolean value. string jsoncontent = '{"isactive":true}'; jsonparser parser = json.createparser(jsoncontent); // advance to the start object marker. parser.nexttoken(); // advance to the next value. parser.nextvalue(); // get the boolean value. boolean isactive = parser.getbooleanvalue(); 3096apex reference guide jsonparser class getcurrentname() returns the name associated with the current token. signature public string getcurrentname() return value type: string usage if the current token is of type jsontoken.field_name, this method returns the same value as gettext. if the current token is a value, this method returns the field name that precedes this token. for other values such as array values or root-level values, this method returns null. the following example parses a sample json string. it advances to the field value and retrieves its corresponding field name. example string jsoncontent = '{"firstname":"john"}'; jsonparser parser = json.createparser(jsoncontent); // advance to the start object marker. parser.nexttoken(); // advance to the next value. parser.nextvalue(); // get the field name for the current value. string fieldname = parser.getcurrentname(); // get the textual representation // of the value. string fieldvalue = parser.gettext(); getcurrenttoken() returns the token that the parser currently points to or null if there's no current token. signature public system.jsontoken getcurrent |
token() return value type: system.jsontoken usage the following example iterates through all the tokens in a sample json string. string jsoncontent = '{"firstname":"john"}'; jsonparser parser = 3097apex reference guide jsonparser class json.createparser(jsoncontent); // advance to the next token. while (parser.nexttoken() != null) { system.debug('current token: ' + parser.getcurrenttoken()); } getdatetimevalue() returns the current token as a date and time value. signature public datetime getdatetimevalue() return value type: datetime usage the current token must be of type jsontoken.value_string and must represent a datetime value in the iso-8601 format. the following example parses a sample json string and retrieves a datetime value. string jsoncontent = '{"transactiondate":"2011-03-22t13:01:23"}'; jsonparser parser = json.createparser(jsoncontent); // advance to the start object marker. parser.nexttoken(); // advance to the next value. parser.nextvalue(); // get the transaction date. datetime transactiondate = parser.getdatetimevalue(); getdatevalue() returns the current token as a date value. signature public date getdatevalue() return value type: date usage the current token must be of type jsontoken.value_string and must represent a date value in the iso-8601 format. 3098apex reference guide jsonparser class the following example parses a sample json string and retrieves a date value. string jsoncontent = '{"dateofbirth":"2011-03-22"}'; jsonparser parser = json.createparser(jsoncontent); // advance to the start object marker. parser.nexttoken(); // advance to the next value. parser.nextvalue(); // get the date of birth. date dob = parser.getdatevalue(); getdecimalvalue() returns the current token as a decimal value. signature public decimal getdecimalvalue() return value type: decimal usage the current token must be of type jsontoken.value_number_float or jsontoken.value_number_int and is a numerical value that can be converted to a value of type decimal. the following example parses a sample json string and retrieves a decimal value. string jsoncontent = '{"gpa":3.8}'; jsonparser parser = json.createparser(jsoncontent); // advance to the start object marker. parser.nexttoken(); // advance to the next value. parser.nextvalue(); // get the gpa score. decimal gpa = parser.getdecimalvalue(); getdoublevalue() returns the current token as a double value. signature public double getdoublevalue() 3099apex reference guide jsonparser class return value type: double usage the current token must be of type jsontoken.value_number_float and is a numerical value that can be converted to a value of type double. the following example parses a sample json string and retrieves a double value. string jsoncontent = '{"gpa":3.8}'; jsonparser parser = json.createparser(jsoncontent); // advance to the start object marker. parser.nexttoken(); // advance to the next value. parser.nextvalue(); // get the gpa score. double gpa = parser.getdoublevalue(); getidvalue() returns the current token as an id value. signature public id getidvalue() return value type: id usage the current token must be of type jsontoken.value_string and must be a valid id. the following example parses a sample json string and retrieves an id value. string jsoncontent = '{"recordid":"001r0000002no6h"}'; jsonparser parser = json.createparser(jsoncontent); // advance to the start object marker. parser.nexttoken(); // advance to the next value. parser.nextvalue(); // get the record id. id recordid = parser.getidvalue(); getintegervalue() returns the current token as an integer value. 3100apex reference guide jsonparser class signature public integer getintegervalue() return value type: integer usage the current token must be of type jsontoken.value_num |
ber_int and must represent an integer. the following example parses a sample json string and retrieves an integer value. string jsoncontent = '{"recordcount":10}'; jsonparser parser = json.createparser(jsoncontent); // advance to the start object marker. parser.nexttoken(); // advance to the next value. parser.nextvalue(); // get the record count. integer count = parser.getintegervalue(); getlastclearedtoken() returns the last token that was cleared by the clearcurrenttoken method. signature public system.jsontoken getlastclearedtoken() return value type: system.jsontoken getlongvalue() returns the current token as a long value. signature public long getlongvalue() return value type: long usage the current token must be of type jsontoken.value_number_int and is a numerical value that can be converted to a value of type long . 3101apex reference guide jsonparser class the following example parses a sample json string and retrieves a long value. string jsoncontent = '{"recordcount":2097531021}'; jsonparser parser = json.createparser(jsoncontent); // advance to the start object marker. parser.nexttoken(); // advance to the next value. parser.nextvalue(); // get the record count. long count = parser.getlongvalue(); gettext() returns the textual representation of the current token or null if there's no current token. signature public string gettext() return value type: string usage no current token exists, and therefore this method returns null, if nexttoken has not been called yet for the first time or if the parser has reached the end of the input stream. gettimevalue() returns the current token as a time value. signature public time gettimevalue() return value type: time usage the current token must be of type jsontoken.value_string and must represent a time value in the iso-8601 format. the following example parses a sample json string and retrieves a datetime value. string jsoncontent = '{"arrivaltime":"18:05"}'; jsonparser parser = json.createparser(jsoncontent); // advance to the start object marker. 3102apex reference guide jsonparser class parser.nexttoken(); // advance to the next value. parser.nextvalue(); // get the arrival time. time arrivaltime = parser.gettimevalue(); hascurrenttoken() returns true if the parser currently points to a token; otherwise, returns false. signature public boolean hascurrenttoken() return value type: boolean nexttoken() returns the next token or null if the parser has reached the end of the input stream. signature public system.jsontoken nexttoken() return value type: system.jsontoken usage advances the stream enough to determine the type of the next token, if any. nextvalue() returns the next token that is a value type or null if the parser has reached the end of the input stream. signature public system.jsontoken nextvalue() return value type: system.jsontoken usage advances the stream enough to determine the type of the next token that is of a value type, if any, including a json array and object start and end markers. 3103apex reference guide jsonparser class readvalueas(apextype) deserializes json content into an object of the specified apex type and returns the deserialized object. signature public object readvalueas(system.type apextype) parameters apextype type: system.type the apextype argument specifies the type of the object that this method returns after deserializing the current value. return value type: object usage if the json content contains attributes not present in the system.type argument, such as a missing field or object, deserialization fails in some circumstances. when deserializing json content into a custom object or an sobject using salesforce api version 34.0 or earlier, this method throws a runtime exception when passed extraneous attributes. when deserializing json content into an apex class in any api version, or into an object in api version 35.0 or later, no exception is thrown. when no exception is thrown, this method ignores extraneous attributes and parses the rest of the json content. example the following example parses a sample json string and retrieves a datetime value. before being able to run this sample, you must create a |
new apex class as follows: public class person { public string name; public string phone; } next, insert the following sample in a class method: // json string that contains a person object. string jsoncontent = '{"person":{' + '"name":"john smith",' + '"phone":"555-1212"}}'; jsonparser parser = json.createparser(jsoncontent); // make calls to nexttoken() // to point to the second // start object marker. parser.nexttoken(); parser.nexttoken(); parser.nexttoken(); // retrieve the person object // from the json string. 3104apex reference guide jsonparser class person obj = (person)parser.readvalueas( person.class); system.assertequals( obj.name, 'john smith'); system.assertequals( obj.phone, '555-1212'); readvalueasstrict(apextype) deserializes json content into an object of the specified apex type and returns the deserialized object. all attributes in the json content must be present in the specified type. signature public object readvalueasstrict(system.type apextype) parameters apextype type: system.type the apextype argument specifies the type of the object that this method returns after deserializing the current value. return value type: object usage if the json content contains attributes not present in the system.type argument, such as a missing field or object, deserialization fails in some circumstances. when deserializing json content with extraneous attributes into an apex class, this method throws an exception in all api versions. however, no exception is thrown when you use this method to deserialize json content into a custom object or an sobject. the following example parses a sample json string and retrieves a datetime value. before being able to run this sample, you must create a new apex class as follows: public class person { public string name; public string phone; } next, insert the following sample in a class method: // json string that contains a person object. string jsoncontent = '{"person":{' + '"name":"john smith",' + '"phone":"555-1212"}}'; jsonparser parser = json.createparser(jsoncontent); // make calls to nexttoken() // to point to the second 3105apex reference guide jsontoken enum // start object marker. parser.nexttoken(); parser.nexttoken(); parser.nexttoken(); // retrieve the person object // from the json string. person obj = (person)parser.readvalueasstrict( person.class); system.assertequals( obj.name, 'john smith'); system.assertequals( obj.phone, '555-1212'); skipchildren() skips all child tokens of type jsontoken.start_array and jsontoken.start_object that the parser currently points to. signature public void skipchildren() return value type: void jsontoken enum contains all token values used for parsing json content. namespace system enum value description end_array the ending of an array value. this token is returned when ']' is encountered. end_object the ending of an object value. this token is returned when '}' is encountered. field_name a string token that is a field name. not_available the requested token isn't available. start_array the start of an array value. this token is returned when '[' is encountered. start_object the start of an object value. this token is returned when '{' is encountered. 3106apex reference guide label class enum value description value_embedded_object an embedded object that isn't accessible as a typical object structure that includes the start and end object tokens start_object and end_object but is represented as a raw object. value_false the literal “false” value. value_null the literal “null” value. value_number_float a float value. value_number_int an integer value. value_string a string value. value_true a value that corresponds to the “true” string literal. label class provides methods to retrieve a custom label or to check if translation exists for a |
label in a specific language and namespace. label names are dynamically resolved at run time, overriding the user’s current language if a translation exists for the requested language. you can’t access labels that are protected in a different namespace. namespace system usage custom labels enable developers to create multilingual applications by automatically presenting information (for example, help text or error messages) in a user’s native language. custom labels have a limit of 1000 characters and can be accessed from apex classes, visualforce pages, lightning pages, or lightning components. for more information on custom labels, see custom labels in salesforce help.the label values can be translated into any language salesforce supports. for supported languages, see supported languages in salesforce help. • to define custom labels, from setup, in the quick find box, enter custom labels, and then select custom labels. • to assign translated values, turn on translation workbench and add translation mappings. • to retrieve the label for a default language setting or for a language and namespace, use system.label.get(namespace, label, language). • to check if translation exists for a label and language in a namespace, use label.translationexists(namespace, label, language). in apex code, you can refer to or instantiate a label like this: system.label.mylabelname for information on passing in labels into aura components, see getting labels in apex in the lightning aura components developer guide. 3107apex reference guide label class examples this example returns true if an english label called mylabel exists in the mynamespace namespace. boolean exists = label.translationexists('mynamespace', 'mylabel', 'en') this example retrieves the custom label translation text for mylabel in french. string value = label.get('mynamespace', 'mylabel', 'fr') in this section: label methods label methods the following are methods for label. in this section: get(namespace, label) retrieve a custom label for the specified namespace and a default language setting. get(namespace, label, language) retrieve a custom label for the specified namespace and language. translationexists(namespace, label, language) check if translation exists for a label and language in a namespace. get(namespace, label) retrieve a custom label for the specified namespace and a default language setting. signature public static string get(string namespace, string label) parameters namespace type: string if the namespace name is null, it defaults to the package namespace. if the namespace name is an empty string, it implies the org namespace. label type: string the label name cannot be null or an empty string. return value type: string 3108apex reference guide label class get(namespace, label, language) retrieve a custom label for the specified namespace and language. signature public static string get(string namespace, string label, string language) parameters namespace type: string if the namespace name is null, it defaults to the package namespace. if the namespace name is an empty string, it implies the org namespace. label type: string the label name cannot be null or an empty string. language type: string this parameter must be a valid language iso code. see the platform-only languages section in supported languages in salesforce help. return value type: string translationexists(namespace, label, language) check if translation exists for a label and language in a namespace. signature public static boolean translationexists(string namespace, string label, string language) parameters namespace type: string if the namespace name is null, it defaults to the package namespace. if the namespace name is an empty string, it implies the org namespace. label type: string the label name cannot be null or an empty string. language type: string this parameter must be a valid language iso code. see the platform-only languages section in supported languages in salesforce help. 3109apex reference guide limits class return value type: boolean limits class contains methods that return limit information for specific resources. namespace system usage the limits methods return the specific limit for the particular governor, such as the number of calls of a method or the amount of heap size remaining. because apex runs in a multitenant environment, the apex runtime engine strictly enforces a number of limits to ensure that runaway apex doesn’t monopolize shared resources. none of the limits methods require an argument. the format of the limits methods |
is as follows: mydmllimit = limits.getdmlstatements(); there are two versions of every method: the first returns the amount of the resource that has been used while the second version contains the word limit and returns the total amount of the resource that is available. see execution governors and limits. limits methods the following are methods for limits. all methods are static. in this section: getaggregatequeries() returns the number of aggregate queries that have been processed with any soql query statement. getlimitaggregatequeries() returns the total number of aggregate queries that can be processed with soql query statements. getasynccalls() reserved for future use. getlimitasynccalls() reserved for future use. getcallouts() returns the number of web service statements that have been processed. getchildrelationshipsdescribes() deprecated. returns the number of child relationship objects that have been returned. getlimitcallouts() returns the total number of web service statements that can be processed. 3110apex reference guide limits class getcputime() returns the cpu time (in milliseconds) that has been used in the current transaction. getlimitcputime() returns the maximum cpu time (in milliseconds) that can be used in a transaction. getdmlrows() returns the number of records that have been processed with any statement that counts against dml limits, such as dml statements, the database.emptyrecyclebin method, and other methods. getlimitdmlrows() returns the total number of records that can be processed with any statement that counts against dml limits, such as dml statements, the database.emptyrecyclebin method, and other methods. getdmlstatements() returns the number of dml statements (such as insert, update or the database.emptyrecyclebin method) that have been called. getlimitdmlstatements() returns the total number of dml statements or the database.emptyrecyclebin methods that can be called. getemailinvocations() returns the number of email invocations (such as sendemail) that have been called. getlimitemailinvocations() returns the total number of email invocation (such as sendemail) that can be called. getfindsimilarcalls() deprecated. returns the same value as getsoslqueries. the number of findsimilar methods is no longer a separate limit, but is tracked as the number of sosl queries issued. getlimitfindsimilarcalls() deprecated. returns the same value as getlimitsoslqueries. the number of findsimilar methods is no longer a separate limit, but is tracked as the number of sosl queries issued. getfuturecalls() returns the number of methods with the future annotation that have been executed (not necessarily completed). getlimitfuturecalls() returns the total number of methods with the future annotation that can be executed (not necessarily completed). getheapsize() returns the approximate amount of memory (in bytes) that has been used for the heap. getlimitheapsize() returns the total amount of memory (in bytes) that can be used for the heap. getmobilepushapexcalls() returns the number of apex calls that have been used by mobile push notifications during the current metering interval. getlimitmobilepushapexcalls() returns the total number of apex calls that are allowed per transaction for mobile push notifications. getpublishimmediatedml() returns the number of eventbus.publish calls that have been made for platform events configured to publish immediately. 3111apex reference guide limits class getlimitpublishimmediatedml() returns the total number of eventbus.publish statements that can be called for platform events configured to publish immediately. getqueries() returns the number of soql queries that have been issued. getlimitqueries() returns the total number of soql queries that can be issued. getquerylocatorrows() returns the number of records that have been returned by the database.getquerylocator method. getlimitquerylocatorrows() returns the total number of records that can be returned by the database.getquerylocator method. getqueryrows() returns the number of records that have been returned by issuing soql queries. getlimitqueryrows() returns the total number of records that can be returned by issuing soql queries. getqueueablejobs() returns the number of queueable jobs that have been added to the queue per transaction. a queueable job corresponds to a class |
that implements the queueable interface. getlimitqueueablejobs() returns the maximum number of queueable jobs that can be added to the queue per transaction. a queueable job corresponds to a class that implements the queueable interface. getrunas() deprecated. returns the same value as getdmlstatements. getlimitrunas() deprecated. returns the same value as getlimitdmlstatements. getsavepointrollbacks() deprecated. returns the same value as getdmlstatements. getlimitsavepointrollbacks() deprecated. returns the same value as getlimitdmlstatements. getsavepoints() deprecated. returns the same value as getdmlstatements. getlimitsavepoints() deprecated. returns the same value as getlimitdmlstatements. getsoslqueries() returns the number of sosl queries that have been issued. getlimitsoslqueries() returns the total number of sosl queries that can be issued. getaggregatequeries() returns the number of aggregate queries that have been processed with any soql query statement. 3112apex reference guide limits class signature public static integer getaggregatequeries() return value type: integer getlimitaggregatequeries() returns the total number of aggregate queries that can be processed with soql query statements. signature public static integer getlimitaggregatequeries() return value type: integer getasynccalls() reserved for future use. signature public static integer getasynccalls() return value type: integer getlimitasynccalls() reserved for future use. signature public static integer getlimitasynccalls() return value type: integer getcallouts() returns the number of web service statements that have been processed. signature public static integer getcallouts() 3113apex reference guide limits class return value type: integer getchildrelationshipsdescribes() deprecated. returns the number of child relationship objects that have been returned. signature public static integer getchildrelationshipsdescribes() return value type: integer usage note: because describe limits are no longer enforced in any api version, this method is no longer available. in api version 30.0 and earlier, this method is available but is deprecated. getlimitcallouts() returns the total number of web service statements that can be processed. signature public static integer getlimitcallouts() return value type: integer getcputime() returns the cpu time (in milliseconds) that has been used in the current transaction. signature public static integer getcputime() return value type: integer getlimitcputime() returns the maximum cpu time (in milliseconds) that can be used in a transaction. 3114apex reference guide limits class signature public static integer getlimitcputime() return value type: integer getdmlrows() returns the number of records that have been processed with any statement that counts against dml limits, such as dml statements, the database.emptyrecyclebin method, and other methods. signature public static integer getdmlrows() return value type: integer getlimitdmlrows() returns the total number of records that can be processed with any statement that counts against dml limits, such as dml statements, the database.emptyrecyclebin method, and other methods. signature public static integer getlimitdmlrows() return value type: integer getdmlstatements() returns the number of dml statements (such as insert, update or the database.emptyrecyclebin method) that have been called. signature public static integer getdmlstatements() return value type: integer getlimitdmlstatements() returns the total number of dml statements or the database.emptyrecyclebin methods that can be called. 3115apex reference guide limits class signature public static integer getlimitdmlstatements() return value type: integer getemailinvocations() returns the number of email invocations (such as sendemail) that have been called. signature public static integer getemailinvocations() return value type: integer getlimitemailinvocations() returns the total number of email invocation (such as sendemail) that can be called. signature public static integer getlimitemailinvocations() return value type: integer getfindsimilarcalls() dep |
recated. returns the same value as getsoslqueries. the number of findsimilar methods is no longer a separate limit, but is tracked as the number of sosl queries issued. signature public static integer getfindsimilarcalls() return value type: integer getlimitfindsimilarcalls() deprecated. returns the same value as getlimitsoslqueries. the number of findsimilar methods is no longer a separate limit, but is tracked as the number of sosl queries issued. 3116apex reference guide limits class signature public static integer getlimitfindsimilarcalls() return value type: integer getfuturecalls() returns the number of methods with the future annotation that have been executed (not necessarily completed). signature public static integer getfuturecalls() return value type: integer getlimitfuturecalls() returns the total number of methods with the future annotation that can be executed (not necessarily completed). signature public static integer getlimitfuturecalls() return value type: integer getheapsize() returns the approximate amount of memory (in bytes) that has been used for the heap. signature public static integer getheapsize() return value type: integer getlimitheapsize() returns the total amount of memory (in bytes) that can be used for the heap. signature public static integer getlimitheapsize() 3117apex reference guide limits class return value type: integer getmobilepushapexcalls() returns the number of apex calls that have been used by mobile push notifications during the current metering interval. signature public static integer getmobilepushapexcalls() return value type:integer getlimitmobilepushapexcalls() returns the total number of apex calls that are allowed per transaction for mobile push notifications. signature public static integer getlimitmobilepushapexcalls() return value type:integer getpublishimmediatedml() returns the number of eventbus.publish calls that have been made for platform events configured to publish immediately. signature public static integer getpublishimmediatedml() return value type: integer getlimitpublishimmediatedml() returns the total number of eventbus.publish statements that can be called for platform events configured to publish immediately. signature public static integer getlimitpublishimmediatedml() return value type: integer 3118apex reference guide limits class getqueries() returns the number of soql queries that have been issued. signature public static integer getqueries() return value type: integer getlimitqueries() returns the total number of soql queries that can be issued. signature public static integer getlimitqueries() return value type: integer getquerylocatorrows() returns the number of records that have been returned by the database.getquerylocator method. signature public static integer getquerylocatorrows() return value type: integer getlimitquerylocatorrows() returns the total number of records that can be returned by the database.getquerylocator method. signature public static integer getlimitquerylocatorrows() return value type: integer getqueryrows() returns the number of records that have been returned by issuing soql queries. 3119apex reference guide limits class signature public static integer getqueryrows() return value type: integer getlimitqueryrows() returns the total number of records that can be returned by issuing soql queries. signature public static integer getlimitqueryrows() return value type: integer getqueueablejobs() returns the number of queueable jobs that have been added to the queue per transaction. a queueable job corresponds to a class that implements the queueable interface. signature public static integer getqueueablejobs() return value type: integer getlimitqueueablejobs() returns the maximum number of queueable jobs that can be added to the queue per transaction. a queueable job corresponds to a class that implements the queueable interface. signature public static integer getlimitqueueablejobs() return value type: integer getrunas() deprecated. returns the same value as getdmlstatements. 3120apex reference guide limits class signature public static integer getrunas() return value type: integer usage the number of runas methods is no longer a separate limit, but is tracked as the number of |
dml statements issued. getlimitrunas() deprecated. returns the same value as getlimitdmlstatements. signature public static integer getlimitrunas() return value type: integer usage the number of runas methods is no longer a separate limit, but is tracked as the number of dml statements issued. getsavepointrollbacks() deprecated. returns the same value as getdmlstatements. signature public static integer getsavepointrollbacks() return value type: integer usage the number of rollback methods is no longer a separate limit, but is tracked as the number of dml statements issued. getlimitsavepointrollbacks() deprecated. returns the same value as getlimitdmlstatements. signature public static integer getlimitsavepointrollbacks() 3121apex reference guide limits class return value type: integer usage the number of rollback methods is no longer a separate limit, but is tracked as the number of dml statements issued. getsavepoints() deprecated. returns the same value as getdmlstatements. signature public static integer getsavepoints() return value type: integer usage the number of setsavepoint methods is no longer a separate limit, but is tracked as the number of dml statements issued. getlimitsavepoints() deprecated. returns the same value as getlimitdmlstatements. signature public static integer getlimitsavepoints() return value type: integer usage the number of setsavepoint methods is no longer a separate limit, but is tracked as the number of dml statements issued. getsoslqueries() returns the number of sosl queries that have been issued. signature public static integer getsoslqueries() return value type: integer 3122apex reference guide list class getlimitsoslqueries() returns the total number of sosl queries that can be issued. signature public static integer getlimitsoslqueries() return value type: integer list class contains methods for the list collection type. namespace system usage the list methods are all instance methods, that is, they operate on a particular instance of a list. for example, the following removes all elements from mylist: mylist.clear(); even though the clear method does not include any parameters, the list that calls it is its implicit parameter. note: • when using a custom type for the list elements, provide an equals method in your class. apex uses this method to determine equality and uniqueness for your objects. for more information on providing an equals method, see using custom types in map keys and sets. • if the list contains string elements, the elements are case-sensitive. two list elements that differ only by case are considered distinct. for more information on lists, see lists. in this section: list constructors list methods list constructors the following are constructors for list. 3123apex reference guide list class in this section: list<t>() creates a new instance of the list class. a list can hold elements of any data type t. list<t>(listtocopy) creates a new instance of the list class by copying the elements from the specified list. t is the data type of the elements in both lists and can be any data type. list<t>(settocopy) creates a new instance of the list class by copying the elements from the specified set. t is the data type of the elements in the set and list and can be any data type. list<t>() creates a new instance of the list class. a list can hold elements of any data type t. signature public list<t>() example // create a list list<integer> ls1 = new list<integer>(); // add two integers to the list ls1.add(1); ls1.add(2); list<t>(listtocopy) creates a new instance of the list class by copying the elements from the specified list. t is the data type of the elements in both lists and can be any data type. signature public list<t>(list<t> listtocopy) parameters listtocopy type: list<t> the list containing the elements to initialize this list from. t is the data type of the list elements. example list<integer> ls1 = new list<integer>(); ls1.add(1); ls1.add(2); // create a list based on |
an existing one list<integer> ls2 = new list<integer>(ls1); 3124apex reference guide list class // ls2 elements are copied from ls1 system.debug(ls2);// debug|(1, 2) list<t>(settocopy) creates a new instance of the list class by copying the elements from the specified set. t is the data type of the elements in the set and list and can be any data type. signature public list<t>(set<t> settocopy) parameters settocopy type: set<t> the set containing the elements to initialize this list with. t is the data type of the set elements. example set<integer> s1 = new set<integer>(); s1.add(1); s1.add(2); // create a list based on a set list<integer> ls = new list<integer>(s1); // ls elements are copied from s1 system.debug(ls);// debug|(1, 2) list methods the following are methods for list. all are instance methods. in this section: add(listelement) adds an element to the end of the list. add(index, listelement) inserts an element into the list at the specified index position. addall(fromlist) adds all of the elements in the specified list to the list that calls the method. both lists must be of the same type. addall(fromset) add all of the elements in specified set to the list that calls the method. the set and the list must be of the same type. clear() removes all elements from a list, consequently setting the list's length to zero. clone() makes a duplicate copy of a list. 3125apex reference guide list class contains(listelement) returns true if the list contains the specified element. deepclone(preserveid, preservereadonlytimestamps, preserveautonumber) makes a duplicate copy of a list of sobject records, including the sobject records themselves. equals(list2) compares this list with the specified list and returns true if both lists are equal; otherwise, returns false. get(index) returns the list element stored at the specified index. getsobjecttype() returns the token of the sobject type that makes up a list of sobjects. hashcode() returns the hashcode corresponding to this list and its contents. indexof(listelement) returns the index of the first occurrence of the specified element in this list. if this list does not contain the element, returns -1. isempty() returns true if the list has zero elements. iterator() returns an instance of an iterator for this list. remove(index) removes the list element stored at the specified index, returning the element that was removed. set(index, listelement) sets the specified value for the element at the given index. size() returns the number of elements in the list. sort() sorts the items in the list in ascending order. tostring() returns the string representation of the list. add(listelement) adds an element to the end of the list. signature public void add(object listelement) parameters listelement type: object 3126apex reference guide list class return value type: void example list<integer> mylist = new list<integer>(); mylist.add(47); integer mynumber = mylist.get(0); system.assertequals(47, mynumber); add(index, listelement) inserts an element into the list at the specified index position. signature public void add(integer index, object listelement) parameters index type: integer listelement type: object return value type: void example in the following example, a list with six elements is created, and integers are added to the first and second index positions. list<integer> mylist = new integer[6]; mylist.add(0, 47); mylist.add(1, 52); system.assertequals(52, mylist.get(1)); addall(fromlist) adds all of the elements in the specified list to the list that calls the method. both lists must be of the same type. signature public void addall(list fromlist) parameters fromlist type: list 3127apex reference guide list class return value type: void addall(fromset) |
add all of the elements in specified set to the list that calls the method. the set and the list must be of the same type. signature public void addall(set fromset) parameters fromset type: set return value type: void clear() removes all elements from a list, consequently setting the list's length to zero. signature public void clear() return value type: void clone() makes a duplicate copy of a list. signature public list<object> clone() return value type: list<object> usage the cloned list is of the same type as the current list. note that if this is a list of sobject records, the duplicate list will only be a shallow copy of the list. that is, the duplicate will have references to each object, but the sobject records themselves will not be duplicated. for example: to also copy the sobject records, you must use the deepclone method. 3128apex reference guide list class example account a = new account(name='acme', billingcity='new york'); account b = new account(); account[] q1 = new account[]{a,b}; account[] q2 = q1.clone(); q1[0].billingcity = 'san francisco'; system.assertequals( 'san francisco', q1[0].billingcity); system.assertequals( 'san francisco', q2[0].billingcity); contains(listelement) returns true if the list contains the specified element. signature public boolean contains(object listelement) parameters listelement type: object return value type: boolean example list<string> mystrings = new list<string>{'a', 'b'}; boolean result = mystrings.contains('z'); system.assertequals(false, result); deepclone(preserveid, preservereadonlytimestamps, preserveautonumber) makes a duplicate copy of a list of sobject records, including the sobject records themselves. signature public list<object> deepclone(boolean preserveid, boolean preservereadonlytimestamps, boolean preserveautonumber) 3129apex reference guide list class parameters preserveid type: boolean the optional preserveid argument determines whether the ids of the original objects are preserved or cleared in the duplicates. if set to true, the ids are copied to the cloned objects. the default is false, that is, the ids are cleared. preservereadonlytimestamps type: boolean the optional preservereadonlytimestamps argument determines whether the read-only timestamp and user id fields are preserved or cleared in the duplicates. if set to true, the read-only fields createdbyid, createddate, lastmodifiedbyid, and lastmodifieddate are copied to the cloned objects. the default is false, that is, the values are cleared. preserveautonumber type: boolean the optional preserveautonumber argument determines whether the autonumber fields of the original objects are preserved or cleared in the duplicates. if set to true, auto number fields are copied to the cloned objects. the default is false, that is, auto number fields are cleared. return value type: list<object> usage the returned list is of the same type as the current list. note: • deepclone only works with lists of sobjects, not with lists of primitives. • for apex saved using salesforce api version 22.0 or earlier, the default value for the preserve_id argument is true, that is, the ids are preserved. to make a shallow copy of a list without duplicating the sobject records it contains, use the clone method. example this example performs a deep clone for a list with two accounts. account a = new account(name='acme', billingcity='new york'); account b = new account(name='salesforce'); account[] q1 = new account[]{a,b}; account[] q2 = q1.deepclone(); q1[0].billingcity = 'san francisco'; system.assertequals( 'san francisco', q1[0].billingcity); 3130apex reference guide list class system.assertequals( 'new york', q2[0].billingcity); this example is based on the previous example and shows how to clone a list with preserved read-only timestamp and user id fields. insert q1 |
; list<account> accts = [select createdbyid, createddate, lastmodifiedbyid, lastmodifieddate, billingcity from account where name='acme' or name='salesforce']; // clone list while preserving timestamp and user id fields. account[] q3 = accts.deepclone(false,true,false); // verify timestamp fields are preserved for the first list element. system.assertequals( accts[0].createdbyid, q3[0].createdbyid); system.assertequals( accts[0].createddate, q3[0].createddate); system.assertequals( accts[0].lastmodifiedbyid, q3[0].lastmodifiedbyid); system.assertequals( accts[0].lastmodifieddate, q3[0].lastmodifieddate); equals(list2) compares this list with the specified list and returns true if both lists are equal; otherwise, returns false. signature public boolean equals(list list2) parameters list2 type: list the list to compare this list with. return value type: boolean usage two lists are equal if their elements are equal and are in the same order. the == operator is used to compare the elements of the lists. 3131apex reference guide list class the == operator is equivalent to calling the equals method, so you can call list1.equals(list2); instead of list1 == list2;. get(index) returns the list element stored at the specified index. signature public object get(integer index) parameters index type: integer return value type: object usage to reference an element of a one-dimensional list of primitives or sobjects, you can also follow the name of the list with the element's index position in square brackets as shown in the example. example list<integer> mylist = new list<integer>(); mylist.add(47); integer mynumber = mylist.get(0); system.assertequals(47, mynumber); list<string> colors = new string[3]; colors[0] = 'red'; colors[1] = 'blue'; colors[2] = 'green'; getsobjecttype() returns the token of the sobject type that makes up a list of sobjects. signature public schema.sobjecttype getsobjecttype() return value type: schema.sobjecttype 3132 |
apex reference guide list class usage use this method with describe information to determine if a list contains sobjects of a particular type. note that this method can only be used with lists that are composed of sobjects. for more information, see understanding apex describe information. example // create a generic sobject variable. sobject sobj = database.query('select id from account limit 1'); // verify if that sobject variable is an account token. system.assertequals( account.sobjecttype, sobj.getsobjecttype()); // create a list of generic sobjects. list<sobject> q = new account[]{}; // verify if the list of sobjects // contains account tokens. system.assertequals( account.sobjecttype, q.getsobjecttype()); hashcode() returns the hashcode corresponding to this list and its contents. signature public integer hashcode() return value type: integer indexof(listelement) returns the index of the first occurrence of the specified element in this list. if this list does not contain the element, returns -1. signature public integer indexof(object listelement) parameters listelement type: object 3133apex reference guide list class return value type: integer example list<string> mystrings = new list<string>{'a', 'b', 'a'}; integer result = mystrings.indexof('a'); system.assertequals(0, result); isempty() returns true if the list has zero elements. signature public boolean isempty() return value type: boolean iterator() returns an instance of an iterator for this list. signature public iterator iterator() return value type: iterator usage from the returned iterator, you can use the iterable methods hasnext and next to iterate through the list. note: you don’t have to implement the iterable interface to use the iterable methods with a list. see custom iterators. example public class customiterator implements iterator<account>{ private list<account> accounts; private integer currentindex; public customiterator(list<account> accounts){ this.accounts = accounts; 3134apex reference guide list class this.currentindex = 0; } public boolean hasnext(){ return currentindex < accounts.size(); } public account next(){ if(hasnext()) { return accounts[currentindex++]; } else { throw new nosuchelementexception('iterator has no more elements.'); } } } remove(index) removes the list element stored at the specified index, returning the element that was removed. signature public object remove(integer index) parameters index type: integer return value type: object example list<string> colors = new string[3]; colors[0] = 'red'; colors[1] = 'blue'; colors[2] = 'green'; string s1 = colors.remove(2); system.assertequals('green', s1); set(index, listelement) sets the specified value for the element at the given index. signature public void set(integer index, object listelement) 3135apex reference guide list class parameters index type: integer the index of the list element to set. listelement type: object the value of the list element to set. return value type: void usage to set an element of a one-dimensional list of primitives or sobjects, you can also follow the name of the list with the element's index position in square brackets. example list<integer> mylist = new integer[6]; mylist.set(0, 47); mylist.set(1, 52); system.assertequals(52, mylist.get(1)); list<string> colors = new string[3]; colors[0] = 'red'; colors[1] = 'blue'; colors[2] = 'green'; size() returns the number of elements in the list. signature public integer size() return value type: integer example list<integer> mylist = new list<integer>(); integer size = mylist.size(); system.assertequals(0, size); list<integer> mylist2 = new integer[6]; 3136apex reference guide list class integer size |
2 = mylist2.size(); system.assertequals(6, size2); sort() sorts the items in the list in ascending order. signature public void sort() return value type: void usage using this method, you can sort primitive types, selectoption elements, and sobjects (standard objects and custom objects). for more information on the sort order used for sobjects, see sorting lists of sobjects. you can also sort custom types (your apex classes) if they implement the comparable interface interface. when you use sort() methods on list<id>s that contain both 15-character and 18-character ids, ids for the same record sort together in api version 35.0 and later. example in the following example, the list has three elements. when the list is sorted, the first element is null because it has no value assigned. the second element and third element have values of 5 and 10. list<integer> q1 = new integer[3]; // assign values to the first two elements. q1[0] = 10; q1[1] = 5; q1.sort(); // verify sorted list. elements are sorted in nulls-first order: null, 5, and 10 system.assertequals(null, q1.get(0)); system.assertequals(5, q1.get(1)); system.assertequals(10, q1.get(2)); 3137apex reference guide location class tostring() returns the string representation of the list. signature public string tostring() return value type: string usage when used in cyclic references, the output is truncated to prevent infinite recursion. when used with large collections, the output is truncated to avoid exceeding total heap size and maximum cpu time. • up to 10 items per collection are included in the output, followed by an ellipsis (…). • if the same object is included multiple times in a collection, it’s shown in the output only once; subsequent references are shown as (already output). location class contains methods for accessing the component fields of geolocation compound fields. namespace system usage each of these methods is also equivalent to a read-only property. for each getter method you can access the property using dot notation. for example, mylocation.getlatitude() is equivalent to mylocation.latitude. you can’t use dot notation to access compound fields’ subfields directly on the parent field. instead, assign the parent field to a variable of type location, and then access its components. location loc = myaccount.mylocation__c; double lat = loc.latitude; important: “location” in salesforce can also refer to the location standard object. when referencing the location object in your apex code, always use schema.location instead of location to prevent confusion with the standard location compound field. if referencing both the location object and the location field in the same snippet, you can differentiate between the two by using system.location for the field and schema.location for the object. example // select and access the location field. mylocation__c is the name of a geolocation field on account. account[] records = [select id, mylocation__c from account limit 10]; 3138apex reference guide location class for(account acct : records) { location loc = acct.mylocation__c; double lat = loc.latitude; double lon = loc.longitude; } // instantiate new location objects and compute the distance between them in different ways. location loc1 = location.newinstance(28.635308,77.22496); location loc2 = location.newinstance(37.7749295,-122.4194155); double dist = location.getdistance(loc1, loc2, 'mi'); double dist2 = loc1.getdistance(loc2, 'mi'); in this section: location methods location methods the following are methods for location. in this section: getdistance(tolocation, unit) calculates the distance between this location and the specified location, using an approximation of the haversine formula and the specified unit. getdistance(firstlocation, secondlocation, unit) calculates the distance between the two specified locations, using an approximation of the haversine formula and the specified unit. getlatitude() returns the latitude field of this location. getlongitude() returns the longitude field of this |
location. newinstance(latitude, longitude) creates an instance of the location class, with the specified latitude and longitude. getdistance(tolocation, unit) calculates the distance between this location and the specified location, using an approximation of the haversine formula and the specified unit. signature public double getdistance(location tolocation, string unit) parameters tolocation type: location 3139apex reference guide location class the location to which you want to calculate the distance from the current location. unit type: string the distance unit you want to use: mi or km. return value type: double getdistance(firstlocation, secondlocation, unit) calculates the distance between the two specified locations, using an approximation of the haversine formula and the specified unit. signature public static double getdistance(location firstlocation, location secondlocation, string unit) parameters firstlocation type: location the first of two locations used to calculate distance. secondlocation type: location the second of two locations used to calculate distance. unit type: string the distance unit you want to use: mi or km. return value type: double getlatitude() returns the latitude field of this location. signature public double getlatitude() return value type: double 3140apex reference guide logginglevel enum getlongitude() returns the longitude field of this location. signature public double getlongitude() return value type: double newinstance(latitude, longitude) creates an instance of the location class, with the specified latitude and longitude. signature public static location newinstance(decimal latitude, decimal longitude) parameters latitude type: decimal longitude type: decimal return value type: location logginglevel enum specifies the logging level for the system.debug method. enum values the following are the values of the system.logginglevel enum, listed from the lowest to the highest levels. the level is cumulative, that is, if you select fine, the log also includes all events logged at the debug, info, warn, and error levels. value description none no logging. error error and exception logging. warn warning logging. info informational logging. debug user-specified debug logging. 3141apex reference guide long class value description fine high level of logging. finer higher level of logging than fine. finest highest level of logging. usage log levels are cumulative. for example, if the lowest level, error, is specified for apex code, only system.debug methods with the log level of error are logged. if the next log level, warn, is specified, system.debug methods specified with either error or warn levels are logged. in this example, if the log level is set to error, the string msgtxt isn’t written to the debug log because the debug method has a level of info. system.debug(logginglevel.info, 'msgtxt'); for more information on log levels, see debug log levels in salesforce help. long class contains methods for the long primitive data type. namespace system usage for more information on long, see long data type. long methods the following are methods for long. in this section: format() returns the string format for this long using the locale of the context user. intvalue() returns the integer value for this long. valueof(stringtolong) returns a long that contains the value of the specified string. as in java, the string is interpreted as representing a signed decimal long. 3142apex reference guide long class format() returns the string format for this long using the locale of the context user. signature public string format() return value type: string example long mylong = 4271990; system.assertequals('4,271,990', mylong.format()); intvalue() returns the integer value for this long. signature public integer intvalue() return value type: integer example long mylong = 7191991; integer value = mylong.intvalue(); system.assertequals(7191991, mylong.intvalue()); valueof(stringtolong) returns a long that contains the value of the specified string. as in java, the string is interpreted as representing a signed decimal long. signature public static long valueof(string stringtolong) parameters stringtolong type: string |
return value type: long 3143apex reference guide map class example long l1 = long.valueof('123456789'); map class contains methods for the map collection type. namespace system usage the map methods are all instance methods, that is, they operate on a particular instance of a map. the following are the instance methods for maps. note: • map keys and values can be of any data type—primitive types, collections, sobjects, user-defined types, and built-in apex types. • uniqueness of map keys of user-defined types is determined by the equals and hashcode methods, which you provide in your classes. uniqueness of keys of all other non-primitive types, such as sobject keys, is determined by comparing the objects’ field values. • map keys of type string are case-sensitive. two keys that differ only by the case are considered unique and have corresponding distinct map entries. subsequently, the map methods, including put, get, containskey, and remove treat these keys as distinct. for more information on maps, see maps. in this section: map constructors map methods map constructors the following are constructors for map. in this section: map<t1,t2>() creates a new instance of the map class. t1 is the data type of the keys and t2 is the data type of the values. map<t1,t2>(maptocopy) creates a new instance of the map class and initializes it by copying the entries from the specified map. t1 is the data type of the keys and t2 is the data type of the values. map<id,sobject>(recordlist) creates a new instance of the map class and populates it with the passed-in list of sobject records. the keys are populated with the sobject ids and the values are the sobjects. 3144apex reference guide map class map<t1,t2>() creates a new instance of the map class. t1 is the data type of the keys and t2 is the data type of the values. signature public map<t1,t2>() example map<integer, string> m1 = new map<integer, string>(); m1.put(1, 'first item'); m1.put(2, 'second item'); map<t1,t2>(maptocopy) creates a new instance of the map class and initializes it by copying the entries from the specified map. t1 is the data type of the keys and t2 is the data type of the values. signature public map<t1,t2>(map<t1,t2> maptocopy) parameters maptocopy type: map<t1, t2> the map to initialize this map with. t1 is the data type of the keys and t2 is the data type of the values. all map keys and values are copied to this map. example map<integer, string> m1 = new map<integer, string>(); m1.put(1, 'first item'); m1.put(2, 'second item'); map<integer, string> m2 = new map<integer, string>(m1); // the map elements of m2 are copied from m1 system.debug(m2); map<id,sobject>(recordlist) creates a new instance of the map class and populates it with the passed-in list of sobject records. the keys are populated with the sobject ids and the values are the sobjects. signature public map<id,sobject>(list<sobject> recordlist) 3145apex reference guide map class parameters recordlist type: list<sobject> the list of sobjects to populate the map with. example list<account> ls = [select id,name from account]; map<id, account> m = new map<id, account>(ls); map methods the following are methods for map. all are instance methods. in this section: clear() removes all of the key-value mappings from the map. clone() makes a duplicate copy of the map. containskey(key) returns true if the map contains a mapping for the specified key. deepclone() makes a duplicate copy of a map, including sobject records if this is a map with sobject record values. equals(map2) comp |
ares this map with the specified map and returns true if both maps are equal; otherwise, returns false. get(key) returns the value to which the specified key is mapped, or null if the map contains no value for this key. getsobjecttype() returns the token of the sobject type that makes up the map values. hashcode() returns the hashcode corresponding to this map. isempty() returns true if the map has zero key-value pairs. keyset() returns a set that contains all of the keys in the map. put(key, value) associates the specified value with the specified key in the map. putall(frommap) copies all of the mappings from the specified map to the original map. putall(sobjectarray) adds the list of sobject records to a map declared as map<id, sobject> or map<string, sobject>. 3146apex reference guide map class remove(key) removes the mapping for the specified key from the map, if present, and returns the corresponding value. size() returns the number of key-value pairs in the map. tostring() returns the string representation of the map. values() returns a list that contains all the values in the map. clear() removes all of the key-value mappings from the map. signature public void clear() return value type: void clone() makes a duplicate copy of the map. signature public map<object, object> clone() return value type: map (of same type) usage if this is a map with sobject record values, the duplicate map will only be a shallow copy of the map. that is, the duplicate will have references to each sobject record, but the records themselves are not duplicated. for example: to also copy the sobject records, you must use the deepclone method. example account a = new account( name='acme', billingcity='new york'); map<integer, account> map1 = new map<integer, account> {}; map1.put(1, a); map<integer, account> map2 = map1.clone(); 3147apex reference guide map class map1.get(1).billingcity = 'san francisco'; system.assertequals( 'san francisco', map1.get(1).billingcity); system.assertequals( 'san francisco', map2.get(1).billingcity); containskey(key) returns true if the map contains a mapping for the specified key. signature public boolean containskey(object key) parameters key type: object return value type: boolean usage if the key is a string, the key value is case-sensitive. example map<string, string> colorcodes = new map<string, string>(); colorcodes.put('red', 'ff0000'); colorcodes.put('blue', '0000a0'); boolean contains = colorcodes.containskey('blue'); system.assertequals(true, contains); deepclone() makes a duplicate copy of a map, including sobject records if this is a map with sobject record values. signature public map<object, object> deepclone() 3148apex reference guide map class return value type: map (of the same type) usage to make a shallow copy of a map without duplicating the sobject records it contains, use the clone() method. example account a = new account( name='acme', billingcity='new york'); map<integer, account> map1 = new map<integer, account> {}; map1.put(1, a); map<integer, account> map2 = map1.deepclone(); // update the first entry of map1 map1.get(1).billingcity = 'san francisco'; // verify that the billingcity is updated in map1 but not in map2 system.assertequals('san francisco', map1.get(1).billingcity); system.assertequals('new york', map2.get(1).billingcity); equals(map2) compares this map with the specified map and returns true if both maps are equal; otherwise, returns false. signature public boolean equals(map map2) parameters map2 type: map the map2 argument is the map to compare this map with. |
return value type: boolean usage two maps are equal if their key/value pairs are identical, regardless of the order of those pairs. the == operator is used to compare the map keys and values. the == operator is equivalent to calling the equals method, so you can call map1.equals(map2); instead of map1 == map2;. 3149apex reference guide map class get(key) returns the value to which the specified key is mapped, or null if the map contains no value for this key. signature public object get(object key) parameters key type: object return value type: object usage if the key is a string, the key value is case-sensitive. example map<string, string> colorcodes = new map<string, string>(); colorcodes.put('red', 'ff0000'); colorcodes.put('blue', '0000a0'); string code = colorcodes.get('blue'); system.assertequals('0000a0', code); // the following is not a color in the map string code2 = colorcodes.get('magenta'); system.assertequals(null, code2); getsobjecttype() returns the token of the sobject type that makes up the map values. signature public schema.sobjecttype getsobjecttype() return value type: schema.sobjecttype usage use this method with describe information, to determine if a map contains sobjects of a particular type. 3150apex reference guide map class note that this method can only be used with maps that have sobject values. for more information, see understanding apex describe information. example // create a generic sobject variable. sobject sobj = database.query('select id from account limit 1'); // verify if that sobject variable is an account token. system.assertequals( account.sobjecttype, sobj.getsobjecttype()); // create a map of generic sobjects map<integer, account> m = new map<integer, account>(); // verify if the map contains account tokens. system.assertequals( account.sobjecttype, m.getsobjecttype()); hashcode() returns the hashcode corresponding to this map. signature public integer hashcode() return value type: integer isempty() returns true if the map has zero key-value pairs. signature public boolean isempty() return value type: boolean example map<string, string> colorcodes = new map<string, string>(); boolean empty = colorcodes.isempty(); system.assertequals(true, empty); 3151apex reference guide map class keyset() returns a set that contains all of the keys in the map. signature public set<object> keyset() return value type: set (of key type) example map<string, string> colorcodes = new map<string, string>(); colorcodes.put('red', 'ff0000'); colorcodes.put('blue', '0000a0'); set <string> colorset = new set<string>(); colorset = colorcodes.keyset(); put(key, value) associates the specified value with the specified key in the map. signature public object put(object key, object value) parameters key type: object value type: object return value type: object usage if the map previously contained a mapping for this key, the old value is returned by the method and then replaced. if the key is a string, the key value is case-sensitive. example map<string, string> colorcodes = new map<string, string>(); 3152apex reference guide map class colorcodes.put('red', 'ff0000'); colorcodes.put('red', '#ff0000'); // red is now #ff0000 putall(frommap) copies all of the mappings from the specified map to the original map. signature public void putall(map frommap) parameters frommap type: map return value type: void usage the new mappings from frommap replace any mappings that the original map had. example map<string, string> map1 = new map<string, string>(); map1.put('red','ff0000'); map<string, string> map2 = new map<string, string>(); |
map2.put('blue','0000ff'); // add map1 entries to map2 map2.putall(map1); system.assertequals(2, map2.size()); putall(sobjectarray) adds the list of sobject records to a map declared as map<id, sobject> or map<string, sobject>. signature public void putall(sobject[] sobjectarray) parameters sobjectarray type: sobject[] return value type: void 3153apex reference guide map class usage this method is similar to calling the map constructor with the same input. example list<account> accts = new list<account>(); accts.add(new account(name='account1')); accts.add(new account(name='account2')); // insert accounts so their ids are populated. insert accts; map<id, account> m = new map<id, account>(); // add all the records to the map. m.putall(accts); system.assertequals(2, m.size()); remove(key) removes the mapping for the specified key from the map, if present, and returns the corresponding value. signature public object remove(key key) parameters key type: key return value type: object usage if the key is a string, the key value is case-sensitive. example map<string, string> colorcodes = new map<string, string>(); colorcodes.put('red', 'ff0000'); colorcodes.put('blue', '0000a0'); string mycolor = colorcodes.remove('blue'); string code2 = colorcodes.get('blue'); system.assertequals(null, code2); size() returns the number of key-value pairs in the map. 3154apex reference guide map class signature public integer size() return value type: integer example map<string, string> colorcodes = new map<string, string>(); colorcodes.put('red', 'ff0000'); colorcodes.put('blue', '0000a0'); integer msize = colorcodes.size(); system.assertequals(2, msize); tostring() returns the string representation of the map. signature public string tostring() return value type: string usage when used in cyclic references, the output is truncated to prevent infinite recursion. when used with large collections, the output is truncated to avoid exceeding total heap size and maximum cpu time. • up to 10 items per collection are included in the output, followed by an ellipsis (…). • if the same object is included multiple times in a collection, it’s shown in the output only once; subsequent references are shown as (already output). values() returns a list that contains all the values in the map. signature public list<object> values() return value type: list<object> 3155apex reference guide matcher class usage the order of map elements is deterministic. you can rely on the order being the same in each subsequent execution of the same code. for example, suppose the values() method returns a list containing value1 and index 0 and value2 and index 1. subsequent runs of the same code result in those values being returned in the same order. example map<string, string> colorcodes = new map<string, string>(); colorcodes.put('red', 'ff0000'); colorcodes.put('blue', '0000a0'); list<string> colors = new list<string>(); colors = colorcodes.values(); matcher class matchers use patterns to perform match operations on a character string. namespace system matcher methods the following are methods for matcher. in this section: end() returns the position after the last matched character. end(groupindex) returns the position after the last character of the subsequence captured by the group index during the previous match operation. if the match was successful but the group itself did not match anything, this method returns -1. find() attempts to find the next subsequence of the input sequence that matches the pattern. this method returns true if a subsequence of the input sequence matches this matcher object's pattern. find(group) resets the matcher object and then tries to find the next subsequence of the input sequence that matches the |
pattern. this method returns true if a subsequence of the input sequence matches this matcher object's pattern. group() returns the input subsequence returned by the previous match. group(groupindex) returns the input subsequence captured by the specified group index during the previous match operation. if the match was successful but the specified group failed to match any part of the input sequence, null is returned. 3156apex reference guide matcher class groupcount() returns the number of capturing groups in this matching object's pattern. group zero denotes the entire pattern and is not included in this count. hasanchoringbounds() returns true if the matcher object has anchoring bounds, false otherwise. by default, a matcher object uses anchoring bounds regions. hastransparentbounds() returns true if the matcher object has transparent bounds, false if it uses opaque bounds. by default, a matcher object uses opaque region boundaries. hitend() returns true if the end of input was found by the search engine in the last match operation performed by this matcher object. when this method returns true, it is possible that more input would have changed the result of the last search. lookingat() attempts to match the input sequence, starting at the beginning of the region, against the pattern. matches() attempts to match the entire region against the pattern. pattern() returns the pattern object from which this matcher object was created. quotereplacement(inputstring) returns a literal replacement string for the specified string inputstring. the characters in the returned string match the sequence of characters in inputstring. region(start, end) sets the limits of this matcher object's region. the region is the part of the input sequence that is searched to find a match. regionend() returns the end index (exclusive) of this matcher object's region. regionstart() returns the start index (inclusive) of this matcher object's region. replaceall(replacementstring) replaces every subsequence of the input sequence that matches the pattern with the replacement string. replacefirst(replacementstring) replaces the first subsequence of the input sequence that matches the pattern with the replacement string. requireend() returns true if more input could change a positive match into a negative one. reset() resets this matcher object. resetting a matcher object discards all of its explicit state information. reset(inputsequence) resets this matcher object with the new input sequence. resetting a matcher object discards all of its explicit state information. start() returns the start index of the first character of the previous match. 3157apex reference guide matcher class start(groupindex) returns the start index of the subsequence captured by the group specified by the group index during the previous match operation. captured groups are indexed from left to right, starting at one. group zero denotes the entire pattern, so the expression m.start(0) is equivalent to m.start(). useanchoringbounds(anchoringbounds) sets the anchoring bounds of the region for the matcher object. by default, a matcher object uses anchoring bounds regions. usepattern(pattern) changes the pattern object that the matcher object uses to find matches. this method causes the matcher object to lose information about the groups of the last match that occurred. the matcher object's position in the input is maintained. usetransparentbounds(transparentbounds) sets the transparency bounds for this matcher object. by default, a matcher object uses anchoring bounds regions. end() returns the position after the last matched character. signature public integer end() return value type: integer end(groupindex) returns the position after the last character of the subsequence captured by the group index during the previous match operation. if the match was successful but the group itself did not match anything, this method returns -1. signature public integer end(integer groupindex) parameters groupindex type: integer return value type: integer usage captured groups are indexed from left to right, starting at one. group zero denotes the entire pattern, so the expressionm.end(0) is equivalent to m.end(). see understanding capturing groups. 3158apex reference guide matcher class find() attempts to find the next subsequence of the input sequence that matches the pattern. this method returns true if a subsequence of the input sequence matches this matcher object's pattern. signature public boolean find() return value type: boolean usage this method starts at |
the beginning of this matcher object's region, or, if a previous invocation of the method was successful and the matcher object has not since been reset, at the first character not matched by the previous match. if the match succeeds, more information can be obtained using the start, end, and group methods. for more information, see using regions. find(group) resets the matcher object and then tries to find the next subsequence of the input sequence that matches the pattern. this method returns true if a subsequence of the input sequence matches this matcher object's pattern. signature public boolean find(integer group) parameters group type: integer return value type: boolean usage if the match succeeds, more information can be obtained using the start, end, and group methods. group() returns the input subsequence returned by the previous match. signature public string group() 3159apex reference guide matcher class return value type: string usage note that some groups, such as (a*), match the empty string. this method returns the empty string when such a group successfully matches the empty string in the input. group(groupindex) returns the input subsequence captured by the specified group index during the previous match operation. if the match was successful but the specified group failed to match any part of the input sequence, null is returned. signature public string group(integer groupindex) parameters groupindex type: integer return value type: string usage captured groups are indexed from left to right, starting at one. group zero denotes the entire pattern, so the expression m.group(0) is equivalent to m.group(). note that some groups, such as (a*), match the empty string. this method returns the empty string when such a group successfully matches the empty string in the input. see understanding capturing groups. groupcount() returns the number of capturing groups in this matching object's pattern. group zero denotes the entire pattern and is not included in this count. signature public integer groupcount() return value type: integer usage see understanding capturing groups. 3160apex reference guide matcher class hasanchoringbounds() returns true if the matcher object has anchoring bounds, false otherwise. by default, a matcher object uses anchoring bounds regions. signature public boolean hasanchoringbounds() return value type: boolean usage if a matcher object uses anchoring bounds, the boundaries of this matcher object's region match start and end of line anchors such as ^ and $. for more information, see using bounds. hastransparentbounds() returns true if the matcher object has transparent bounds, false if it uses opaque bounds. by default, a matcher object uses opaque region boundaries. signature public boolean hastransparentbounds() return value type: boolean usage for more information, see using bounds. hitend() returns true if the end of input was found by the search engine in the last match operation performed by this matcher object. when this method returns true, it is possible that more input would have changed the result of the last search. signature public boolean hitend() return value type: boolean lookingat() attempts to match the input sequence, starting at the beginning of the region, against the pattern. 3161apex reference guide matcher class signature public boolean lookingat() return value type: boolean usage like the matches method, this method always starts at the beginning of the region; unlike that method, it does not require the entire region be matched. if the match succeeds, more information can be obtained using the start, end, and group methods. see using regions. matches() attempts to match the entire region against the pattern. signature public boolean matches() return value type: boolean usage if the match succeeds, more information can be obtained using the start, end, and group methods. see using regions. pattern() returns the pattern object from which this matcher object was created. signature public pattern object pattern() return value type: system.pattern quotereplacement(inputstring) returns a literal replacement string for the specified string inputstring. the characters in the returned string match the sequence of characters in inputstring. 3162apex reference guide matcher class signature public static string quotereplacement(string inputstring) parameters inputstring type: string return value type: string usage metacharacters (such as $ or ^) and |
escape sequences in the input string are treated as literal characters with no special meaning. region(start, end) sets the limits of this matcher object's region. the region is the part of the input sequence that is searched to find a match. signature public matcher object region(integer start, integer end) parameters start type: integer end type: integer return value type: matcher usage this method first resets the matcher object, then sets the region to start at the index specified by start and end at the index specified by end. depending on the transparency boundaries being used, certain constructs such as anchors may behave differently at or around the boundaries of the region. see using regions and using bounds. regionend() returns the end index (exclusive) of this matcher object's region. 3163apex reference guide matcher class signature public integer regionend() return value type: integer usage see using regions. regionstart() returns the start index (inclusive) of this matcher object's region. signature public integer regionstart() return value type: integer usage see using regions. replaceall(replacementstring) replaces every subsequence of the input sequence that matches the pattern with the replacement string. signature public string replaceall(string replacementstring) parameters replacementstring type: string return value type: string usage this method first resets the matcher object, then scans the input sequence looking for matches of the pattern. characters that are not part of any match are appended directly to the result string; each match is replaced in the result by the replacement string. the replacement string may contain references to captured subsequences. 3164apex reference guide matcher class note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if the string was treated as a literal replacement string. dollar signs may be treated as references to captured subsequences, and backslashes are used to escape literal characters in the replacement string. invoking this method changes this matcher object's state. if the matcher object is to be used in further matching operations it should first be reset. given the regular expression a*b, the input "aabxyzaabxyzabxyzb", and the replacement string "-", an invocation of this method on a matcher object for that expression would yield the string "-xyz-xyz-xyz-". replacefirst(replacementstring) replaces the first subsequence of the input sequence that matches the pattern with the replacement string. signature public string replacefirst(string replacementstring) parameters replacementstring type: string return value type: string usage note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if the string was treated as a literal replacement string. dollar signs may be treated as references to captured subsequences, and backslashes are used to escape literal characters in the replacement string. invoking this method changes this matcher object's state. if the matcher object is to be used in further matching operations it should first be reset. given the regular expression dog, the input "zzzdogzzzdogzzz", and the replacement string "cat", an invocation of this method on a matcher object for that expression would return the string "zzzcatzzzdogzzz". requireend() returns true if more input could change a positive match into a negative one. signature public boolean requireend() return value type: boolean 3165apex reference guide matcher class usage if this method returns true, and a match was found, then more input could cause the match to be lost. if this method returns false and a match was found, then more input might change the match but the match won't be lost. if a match was not found, then requireend has no meaning. reset() resets this matcher object. resetting a matcher object discards all of its explicit state information. signature public matcher object reset() return value type: matcher usage this method does not change whether the matcher object uses anchoring bounds. you must explicitly use the useanchoringbounds method to change the anchoring bounds. for more information, see using bounds. reset(inputsequence) resets this matcher object with the new input sequence. resetting a matcher object discards all of its explicit state information. signature public matcher reset(string inputsequence) parameters inputsequence |
type: string return value type: matcher start() returns the start index of the first character of the previous match. signature public integer start() 3166apex reference guide matcher class return value type: integer start(groupindex) returns the start index of the subsequence captured by the group specified by the group index during the previous match operation. captured groups are indexed from left to right, starting at one. group zero denotes the entire pattern, so the expression m.start(0) is equivalent to m.start(). signature public integer start(integer groupindex) parameters groupindex type: integer return value type: integer usage see understanding capturing groups. useanchoringbounds(anchoringbounds) sets the anchoring bounds of the region for the matcher object. by default, a matcher object uses anchoring bounds regions. signature public matcher object useanchoringbounds(boolean anchoringbounds) parameters anchoringbounds type: boolean if you specify true, the matcher object uses anchoring bounds. if you specify false, non-anchoring bounds are used. return value type: matcher usage if a matcher object uses anchoring bounds, the boundaries of this matcher object's region match start and end of line anchors such as ^ and $. for more information, see using bounds. 3167apex reference guide math class usepattern(pattern) changes the pattern object that the matcher object uses to find matches. this method causes the matcher object to lose information about the groups of the last match that occurred. the matcher object's position in the input is maintained. signature public matcher object usepattern(pattern pattern) parameters pattern type: system.pattern return value type: matcher usetransparentbounds(transparentbounds) sets the transparency bounds for this matcher object. by default, a matcher object uses anchoring bounds regions. signature public matcher object usetransparentbounds(boolean transparentbounds) parameters transparentbounds type: boolean if you specify true, the matcher object uses transparent bounds. if you specify false, opaque bounds are used. return value type: matcher usage for more information, see using bounds. math class contains methods for mathematical operations. namespace system 3168apex reference guide math class math fields the following are fields for math. in this section: e returns the mathematical constant e, which is the base of natural logarithms. pi returns the mathematical constant pi, which is the ratio of the circumference of a circle to its diameter. e returns the mathematical constant e, which is the base of natural logarithms. signature public static final double e property value type: double pi returns the mathematical constant pi, which is the ratio of the circumference of a circle to its diameter. signature public static final double pi property value type: double math methods the following are methods for math. all methods are static. in this section: abs(decimalvalue) returns the absolute value of the specified decimal. abs(doublevalue) returns the absolute value of the specified double. abs(integervalue) returns the absolute value of the specified integer. abs(longvalue) returns the absolute value of the specified long. 3169apex reference guide math class acos(decimalangle) returns the arc cosine of an angle, in the range of 0.0 through pi. acos(doubleangle) returns the arc cosine of an angle, in the range of 0.0 through pi. asin(decimalangle) returns the arc sine of an angle, in the range of -pi/2 through pi/2. asin(doubleangle) returns the arc sine of an angle, in the range of -pi/2 through pi/2. atan(decimalangle) returns the arc tangent of an angle, in the range of -pi/2 through pi/2. atan(doubleangle) returns the arc tangent of an angle, in the range of -pi/2 through pi/2. atan2(xcoordinate, ycoordinate) converts rectangular coordinates (xcoordinate and ycoordinate) to polar (r and theta). this method computes the phase theta by computing an arc tangent of xcoordinate/ycoordinate in the range of -pi to pi. |
atan2(xcoordinate, ycoordinate) converts rectangular coordinates (xcoordinate and ycoordinate) to polar (r and theta). this method computes the phase theta by computing an arc tangent of xcoordinate/ycoordinate in the range of -pi to pi. cbrt(decimalvalue) returns the cube root of the specified decimal. the cube root of a negative value is the negative of the cube root of that value's magnitude. cbrt(doublevalue) returns the cube root of the specified double. the cube root of a negative value is the negative of the cube root of that value's magnitude. ceil(decimalvalue) returns the smallest (closest to negative infinity) decimal that is not less than the argument and is equal to a mathematical integer. ceil(doublevalue) returns the smallest (closest to negative infinity) double that is not less than the argument and is equal to a mathematical integer. cos(decimalangle) returns the trigonometric cosine of the angle specified by decimalangle. cos(doubleangle) returns the trigonometric cosine of the angle specified by doubleangle. cosh(decimalangle) returns the hyperbolic cosine of decimalangle. the hyperbolic cosine of d is defined to be (ex + e-x)/2 where e is euler's number. cosh(doubleangle) returns the hyperbolic cosine of doubleangle. the hyperbolic cosine of d is defined to be (ex + e-x)/2 where e is euler's number. exp(exponentdecimal) returns euler's number e raised to the power of the specified decimal. exp(exponentdouble) returns euler's number e raised to the power of the specified double. 3170apex reference guide math class floor(decimalvalue) returns the largest (closest to positive infinity) decimal that is not greater than the argument and is equal to a mathematical integer. floor(doublevalue) returns the largest (closest to positive infinity) double that is not greater than the argument and is equal to a mathematical integer. log(decimalvalue) returns the natural logarithm (base e) of the specified decimal. log(doublevalue) returns the natural logarithm (base e) of the specified double. log10(decimalvalue) returns the logarithm (base 10) of the specified decimal. log10(doublevalue) returns the logarithm (base 10) of the specified double. max(decimalvalue1, decimalvalue2) returns the larger of the two specified decimals. max(doublevalue1, doublevalue2) returns the larger of the two specified doubles. max(integervalue1, integervalue2) returns the larger of the two specified integers. max(longvalue1, longvalue2) returns the larger of the two specified longs. min(decimalvalue1, decimalvalue2) returns the smaller of the two specified decimals. min(doublevalue1, doublevalue2) returns the smaller of the two specified doubles. min(integervalue1, integervalue2) returns the smaller of the two specified integers. min(longvalue1, longvalue2) returns the smaller of the two specified longs. mod(integervalue1, integervalue2) returns the remainder of integervalue1 divided by integervalue2. mod(longvalue1, longvalue2) returns the remainder of longvalue1 divided by longvalue2. pow(doublevalue, exponent) returns the value of the first double raised to the power of exponent. random() returns a positive double that is greater than or equal to 0.0 and less than 1.0. rint(decimalvalue) returns the value that is closest in value to decimalvalue and is equal to a mathematical integer. rint(doublevalue) returns the value that is closest in value to doublevalue and is equal to a mathematical integer. 3171apex reference guide math class round(doublevalue) do not use. this method is deprecated as of the winter '08 release. instead, use math.roundtolong. returns the closest integer to the specified double. if the result is less than -2,147,483,648 or greater than 2,147,483,647, apex generates an error. round(decimalvalue) returns the rounded approximation of this decimal. the number |
is rounded to zero decimal places using half-even rounding mode, that is, it rounds towards the “nearest neighbor” unless both neighbors are equidistant, in which case, this mode rounds towards the even neighbor. roundtolong(decimalvalue) returns the rounded approximation of this decimal. the number is rounded to zero decimal places using half-even rounding mode, that is, it rounds towards the “nearest neighbor” unless both neighbors are equidistant, in which case, this mode rounds towards the even neighbor. roundtolong(doublevalue) returns the closest long to the specified double. signum(decimalvalue) returns the signum function of the specified decimal, which is 0 if decimalvalue is 0, 1.0 if decimalvalue is greater than 0, -1.0 if decimalvalue is less than 0. signum(doublevalue) returns the signum function of the specified double, which is 0 if doublevalue is 0, 1.0 if doublevalue is greater than 0, -1.0 if doublevalue is less than 0. sin(decimalangle) returns the trigonometric sine of the angle specified by decimalangle. sin(doubleangle) returns the trigonometric sine of the angle specified by doubleangle. sinh(decimalangle) returns the hyperbolic sine of decimalangle. the hyperbolic sine of decimalangle is defined to be (ex - e-x)/2 where e is euler's number. sinh(doubleangle) returns the hyperbolic sine of doubleangle. the hyperbolic sine of doubleangle is defined to be (ex - e-x)/2 where e is euler's number. sqrt(decimalvalue) returns the correctly rounded positive square root of decimalvalue. sqrt(doublevalue) returns the correctly rounded positive square root of doublevalue. tan(decimalangle) returns the trigonometric tangent of the angle specified by decimalangle. tan(doubleangle) returns the trigonometric tangent of the angle specified by doubleangle. tanh(decimalangle) returns the hyperbolic tangent of decimalangle. the hyperbolic tangent of decimalangle is defined to be (ex - e-x)/(ex + e-x) where e is euler's number. in other words, it is equivalent to sinh(x)/cosinh(x). the absolute value of the exact tanh is always less than 1. 3172apex reference guide math class tanh(doubleangle) returns the hyperbolic tangent of doubleangle. the hyperbolic tangent of doubleangle is defined to be (ex - e-x)/(ex + e-x) where e is euler's number. in other words, it is equivalent to sinh(x)/cosinh(x). the absolute value of the exact tanh is always less than 1. abs(decimalvalue) returns the absolute value of the specified decimal. signature public static decimal abs(decimal decimalvalue) parameters decimalvalue type: decimal return value type: decimal abs(doublevalue) returns the absolute value of the specified double. signature public static double abs(double doublevalue) parameters doublevalue type: double return value type: double abs(integervalue) returns the absolute value of the specified integer. signature public static integer abs(integer integervalue) parameters integervalue type: integer 3173apex reference guide math class return value type: integer example integer i = -42; integer i2 = math.abs(i); system.assertequals(i2, 42); abs(longvalue) returns the absolute value of the specified long. signature public static long abs(long longvalue) parameters longvalue type: long return value type: long acos(decimalangle) returns the arc cosine of an angle, in the range of 0.0 through pi. signature public static decimal acos(decimal decimalangle) parameters decimalangle type: decimal return value type: decimal acos(doubleangle) returns the arc cosine of an angle, in the range of 0.0 through pi. signature public static double acos(double doubleangle) 3174apex reference guide math class |
parameters doubleangle type: double return value type: double asin(decimalangle) returns the arc sine of an angle, in the range of -pi/2 through pi/2. signature public static decimal asin(decimal decimalangle) parameters decimalangle type: decimal return value type: decimal asin(doubleangle) returns the arc sine of an angle, in the range of -pi/2 through pi/2. signature public static double asin(double doubleangle) parameters doubleangle type: double return value type: double atan(decimalangle) returns the arc tangent of an angle, in the range of -pi/2 through pi/2. signature public static decimal atan(decimal decimalangle) 3175apex reference guide math class parameters decimalangle type: decimal return value type: decimal atan(doubleangle) returns the arc tangent of an angle, in the range of -pi/2 through pi/2. signature public static double atan(double doubleangle) parameters doubleangle type: double return value type: double atan2(xcoordinate, ycoordinate) converts rectangular coordinates (xcoordinate and ycoordinate) to polar (r and theta). this method computes the phase theta by computing an arc tangent of xcoordinate/ycoordinate in the range of -pi to pi. signature public static decimal atan2(decimal xcoordinate, decimal ycoordinate) parameters xcoordinate type: decimal ycoordinate type: decimal return value type: decimal atan2(xcoordinate, ycoordinate) converts rectangular coordinates (xcoordinate and ycoordinate) to polar (r and theta). this method computes the phase theta by computing an arc tangent of xcoordinate/ycoordinate in the range of -pi to pi. 3176apex reference guide math class signature public static double atan2(double xcoordinate, double ycoordinate) parameters xcoordinate type: double ycoordinate type: double return value type: double cbrt(decimalvalue) returns the cube root of the specified decimal. the cube root of a negative value is the negative of the cube root of that value's magnitude. signature public static decimal cbrt(decimal decimalvalue) parameters decimalvalue type: decimal return value type: decimal cbrt(doublevalue) returns the cube root of the specified double. the cube root of a negative value is the negative of the cube root of that value's magnitude. signature public static double cbrt(double doublevalue) parameters doublevalue type: double return value type: double 3177apex reference guide math class ceil(decimalvalue) returns the smallest (closest to negative infinity) decimal that is not less than the argument and is equal to a mathematical integer. signature public static decimal ceil(decimal decimalvalue) parameters decimalvalue type: decimal return value type: decimal ceil(doublevalue) returns the smallest (closest to negative infinity) double that is not less than the argument and is equal to a mathematical integer. signature public static double ceil(double doublevalue) parameters doublevalue type: double return value type: double cos(decimalangle) returns the trigonometric cosine of the angle specified by decimalangle. signature public static decimal cos(decimal decimalangle) parameters decimalangle type: decimal return value type: decimal 3178apex reference guide math class cos(doubleangle) returns the trigonometric cosine of the angle specified by doubleangle. signature public static double cos(double doubleangle) parameters doubleangle type: double return value type: double cosh(decimalangle) returns the hyperbolic cosine of decimalangle. the hyperbolic cosine of d is defined to be (ex + e-x)/2 where e is euler's number. signature public static decimal cosh(decimal decimalangle) parameters decimalangle type: decimal return value type |
: decimal cosh(doubleangle) returns the hyperbolic cosine of doubleangle. the hyperbolic cosine of d is defined to be (ex + e-x)/2 where e is euler's number. signature public static double cosh(double doubleangle) parameters doubleangle type: double return value type: double 3179apex reference guide math class exp(exponentdecimal) returns euler's number e raised to the power of the specified decimal. signature public static decimal exp(decimal exponentdecimal) parameters exponentdecimal type: decimal return value type: decimal exp(exponentdouble) returns euler's number e raised to the power of the specified double. signature public static double exp(double exponentdouble) parameters exponentdouble type: double return value type: double floor(decimalvalue) returns the largest (closest to positive infinity) decimal that is not greater than the argument and is equal to a mathematical integer. signature public static decimal floor(decimal decimalvalue) parameters decimalvalue type: decimal return value type: decimal 3180apex reference guide math class floor(doublevalue) returns the largest (closest to positive infinity) double that is not greater than the argument and is equal to a mathematical integer. signature public static double floor(double doublevalue) parameters doublevalue type: double return value type: double log(decimalvalue) returns the natural logarithm (base e) of the specified decimal. signature public static decimal log(decimal decimalvalue) parameters decimalvalue type: decimal return value type: decimal log(doublevalue) returns the natural logarithm (base e) of the specified double. signature public static double log(double doublevalue) parameters doublevalue type: double return value type: double 3181apex reference guide math class log10(decimalvalue) returns the logarithm (base 10) of the specified decimal. signature public static decimal log10(decimal decimalvalue) parameters decimalvalue type: decimal return value type: decimal log10(doublevalue) returns the logarithm (base 10) of the specified double. signature public static double log10(double doublevalue) parameters doublevalue type: double return value type: double max(decimalvalue1, decimalvalue2) returns the larger of the two specified decimals. signature public static decimal max(decimal decimalvalue1, decimal decimalvalue2) parameters decimalvalue1 type: decimal decimalvalue2 type: decimal 3182 |
apex reference guide math class return value type: decimal example decimal larger = math.max(12.3, 156.6); system.assertequals(larger, 156.6); max(doublevalue1, doublevalue2) returns the larger of the two specified doubles. signature public static double max(double doublevalue1, double doublevalue2) parameters doublevalue1 type: double doublevalue2 type: double return value type: double max(integervalue1, integervalue2) returns the larger of the two specified integers. signature public static integer max(integer integervalue1, integer integervalue2) parameters integervalue1 type: integer integervalue2 type: integer return value type: integer max(longvalue1, longvalue2) returns the larger of the two specified longs. 3183apex reference guide math class signature public static long max(long longvalue1, long longvalue2) parameters longvalue1 type: long longvalue2 type: long return value type: long min(decimalvalue1, decimalvalue2) returns the smaller of the two specified decimals. signature public static decimal min(decimal decimalvalue1, decimal decimalvalue2) parameters decimalvalue1 type: decimal decimalvalue2 type: decimal return value type: decimal example decimal smaller = math.min(12.3, 156.6); system.assertequals(smaller, 12.3); min(doublevalue1, doublevalue2) returns the smaller of the two specified doubles. signature public static double min(double doublevalue1, double doublevalue2) 3184apex reference guide math class parameters doublevalue1 type: double doublevalue2 type: double return value type: double min(integervalue1, integervalue2) returns the smaller of the two specified integers. signature public static integer min(integer integervalue1, integer integervalue2) parameters integervalue1 type: integer integervalue2 type: integer return value type: integer min(longvalue1, longvalue2) returns the smaller of the two specified longs. signature public static long min(long longvalue1, long longvalue2) parameters longvalue1 type: long longvalue2 type: long return value type: long 3185apex reference guide math class mod(integervalue1, integervalue2) returns the remainder of integervalue1 divided by integervalue2. signature public static integer mod(integer integervalue1, integer integervalue2) parameters integervalue1 type: integer integervalue2 type: integer return value type: integer example integer remainder = math.mod(12, 2); system.assertequals(remainder, 0); integer remainder2 = math.mod(8, 3); system.assertequals(remainder2, 2); mod(longvalue1, longvalue2) returns the remainder of longvalue1 divided by longvalue2. signature public static long mod(long longvalue1, long longvalue2) parameters longvalue1 type: long longvalue2 type: long return value type: long pow(doublevalue, exponent) returns the value of the first double raised to the power of exponent. 3186apex reference guide math class signature public static double pow(double doublevalue, double exponent) parameters doublevalue type: double exponent type: double return value type: double random() returns a positive double that is greater than or equal to 0.0 and less than 1.0. signature public static double random() return value type: double rint(decimalvalue) returns the value that is closest in value to decimalvalue and is equal to a mathematical integer. signature public static decimal rint(decimal decimalvalue) parameters decimalvalue type: decimal return value type: decimal rint(doublevalue) returns the value that is closest in value to doublevalue and is equal to a mathematical integer. signature public static double rint(double doublevalue) 3187apex reference guide math class parameters doublevalue type: double return value type: double round(doublevalue) do not use. this method |
is deprecated as of the winter '08 release. instead, use math.roundtolong. returns the closest integer to the specified double. if the result is less than -2,147,483,648 or greater than 2,147,483,647, apex generates an error. signature public static integer round(double doublevalue) parameters doublevalue type: double return value type: integer round(decimalvalue) returns the rounded approximation of this decimal. the number is rounded to zero decimal places using half-even rounding mode, that is, it rounds towards the “nearest neighbor” unless both neighbors are equidistant, in which case, this mode rounds towards the even neighbor. signature public static integer round(decimal decimalvalue) parameters decimalvalue type: decimal return value type: integer usage note that this rounding mode statistically minimizes cumulative error when applied repeatedly over a sequence of calculations. 3188apex reference guide math class example decimal d1 = 4.5; integer i1 = math.round(d1); system.assertequals(4, i1); decimal d2 = 5.5; integer i2 = math.round(d2); system.assertequals(6, i2); roundtolong(decimalvalue) returns the rounded approximation of this decimal. the number is rounded to zero decimal places using half-even rounding mode, that is, it rounds towards the “nearest neighbor” unless both neighbors are equidistant, in which case, this mode rounds towards the even neighbor. signature public static long roundtolong(decimal decimalvalue) parameters decimalvalue type: decimal return value type: long usage note that this rounding mode statistically minimizes cumulative error when applied repeatedly over a sequence of calculations. example decimal d1 = 4.5; long i1 = math.roundtolong(d1); system.assertequals(4, i1); decimal d2 = 5.5; long i2 = math.roundtolong(d2); system.assertequals(6, i2); roundtolong(doublevalue) returns the closest long to the specified double. signature public static long roundtolong(double doublevalue) 3189apex reference guide math class parameters doublevalue type: double return value type: long signum(decimalvalue) returns the signum function of the specified decimal, which is 0 if decimalvalue is 0, 1.0 if decimalvalue is greater than 0, -1.0 if decimalvalue is less than 0. signature public static decimal signum(decimal decimalvalue) parameters decimalvalue type: decimal return value type: decimal signum(doublevalue) returns the signum function of the specified double, which is 0 if doublevalue is 0, 1.0 if doublevalue is greater than 0, -1.0 if doublevalue is less than 0. signature public static double signum(double doublevalue) parameters doublevalue type: double return value type: double sin(decimalangle) returns the trigonometric sine of the angle specified by decimalangle. 3190apex reference guide math class signature public static decimal sin(decimal decimalangle) parameters decimalangle type: decimal return value type: decimal sin(doubleangle) returns the trigonometric sine of the angle specified by doubleangle. signature public static double sin(double doubleangle) parameters doubleangle type: double return value type: double sinh(decimalangle) returns the hyperbolic sine of decimalangle. the hyperbolic sine of decimalangle is defined to be (ex - e-x)/2 where e is euler's number. signature public static decimal sinh(decimal decimalangle) parameters decimalangle type: decimal return value type: decimal 3191apex reference guide math class sinh(doubleangle) returns the hyperbolic sine of doubleangle. the hyperbolic sine of doubleangle is defined to be (ex - e-x)/2 where e is euler's number. signature public static double sinh(double doubleangle) parameters doubleangle type: double return value type: double |
sqrt(decimalvalue) returns the correctly rounded positive square root of decimalvalue. signature public static decimal sqrt(decimal decimalvalue) parameters decimalvalue type: decimal return value type: decimal sqrt(doublevalue) returns the correctly rounded positive square root of doublevalue. signature public static double sqrt(double doublevalue) parameters doublevalue type: double return value type: double 3192apex reference guide math class tan(decimalangle) returns the trigonometric tangent of the angle specified by decimalangle. signature public static decimal tan(decimal decimalangle) parameters decimalangle type: decimal return value type: decimal tan(doubleangle) returns the trigonometric tangent of the angle specified by doubleangle. signature public static double tan(double doubleangle) parameters doubleangle type: double return value type: double tanh(decimalangle) returns the hyperbolic tangent of decimalangle. the hyperbolic tangent of decimalangle is defined to be (ex - e-x)/(ex + e-x) where e is euler's number. in other words, it is equivalent to sinh(x)/cosinh(x). the absolute value of the exact tanh is always less than 1. signature public static decimal tanh(decimal decimalangle) parameters decimalangle type: decimal 3193apex reference guide messaging class return value type: decimal tanh(doubleangle) returns the hyperbolic tangent of doubleangle. the hyperbolic tangent of doubleangle is defined to be (ex - e-x)/(ex + e-x) where e is euler's number. in other words, it is equivalent to sinh(x)/cosinh(x). the absolute value of the exact tanh is always less than 1. signature public static double tanh(double doubleangle) parameters doubleangle type: double return value type: double messaging class contains messaging methods used when sending a single or mass email. namespace system messaging methods the following are methods for messaging. all are instance methods. in this section: extractinboundemail(source, includeforwardedattachments) use this method in your email service code to control how to parse and process forwarded or attached emails. returns an instance of messaging.inboundemail from a stream of data that is in rfc822 format. the data stream can be a forwarded email in an attachment to an existing inboundemail, or a stream from another source. reservemassemailcapacity(amountreserved) reserves email capacity to send mass email to the specified number of email addresses, after the current transaction commits. reservesingleemailcapacity(amountreserved) reserves email capacity to send single email to the specified number of email addresses, after the current transaction commits. 3194apex reference guide messaging class sendemail(emails, allornothing) sends the list of emails instantiated with either singleemailmessage or massemailmessage and returns a list of sendemailresult objects. when org preferences are set to save emailmessage objects and a trigger is defined for emailmessage objects, the trigger is fired for each singleemailmessage individually. the sendemail method can be called 10 times per apex transaction and each method invocation can include up to 100 "to", 25 "cc", and 25 "bcc" recipients. sendemailmessage(emailmessageids, allornothing) sends draft email messages as defined by the specified email message ids and returns a list of sendemailresult objects. renderemailtemplate(whoid, whatid, bodies) replaces merge fields in text bodies of email templates with values from salesforce records. returns an array of renderemailtemplatebodyresult objects, each of which corresponds to an element in the supplied array of text bodies. each renderemailtemplatebodyresult provides a success or failure indication, along with either an error code or the rendered text. renderstoredemailtemplate(templateid, whoid, whatid) renders a text, custom, html, or visualforce email template that exists in the database into an instance of messaging.singleemailmessage. includes all attachment content in the returned email message. renderstoredemailtemplate(templateid, whoid, whatid, attachmentretrievaloption) renders a text, |
custom, html, or visualforce email template that exists in the database into an instance of messaging.singleemailmessage. provides options for including attachment metadata only, attachment metadata and content, or excluding attachments. renderstoredemailtemplate(templateid, whoid, whatid, attachmentretrievaloption, updateemailtemplateusage) renders a text, custom, html, or visualforce email template that exists in the database into an instance of messaging.singleemailmessage. provides options for including attachment metadata only, attachment metadata and content, or excluding attachments. extractinboundemail(source, includeforwardedattachments) use this method in your email service code to control how to parse and process forwarded or attached emails. returns an instance of messaging.inboundemail from a stream of data that is in rfc822 format. the data stream can be a forwarded email in an attachment to an existing inboundemail, or a stream from another source. signature public static messaging.inboundemail extractinboundemail(object source, boolean includeforwardedattachments) parameters source type: object an instance of messaging.inboundemail.binaryattachment whose mimetypesubtype is message/rfc822 or a blob. if source is a blob, then supply a byte array in rfc822 format. includeforwardedattachments type: boolean this parameter controls how attachments to embedded or forwarded emails are handled. set to true to provide all attachments, even attachments in embedded emails in the binaryattachments and textattachments properties of the returned value. set to false to provide only the attachments that are at the top level of the source email. 3195apex reference guide messaging class return value type: messaging.inboundemail reservemassemailcapacity(amountreserved) reserves email capacity to send mass email to the specified number of email addresses, after the current transaction commits. signature public void reservemassemailcapacity(integer amountreserved) parameters amountreserved type: integer return value type: void usage this method can be called when you know in advance how many addresses emails will be sent to as a result of the transaction. if the transaction would cause the organization to exceed its daily email limit, using this method results in the following error: system.handledexception: the daily limit for the org would be exceeded by this request.if the organization doesn’t have permission to send api or mass email, using this method results in the following error: system.noaccessexception: the organization is not permitted to send email. reservesingleemailcapacity(amountreserved) reserves email capacity to send single email to the specified number of email addresses, after the current transaction commits. signature public void reservesingleemailcapacity(integer amountreserved) parameters amountreserved type: integer return value type: void usage this method can be called when you know in advance how many addresses emails will be sent to as a result of the transaction. if the transaction would cause the organization to exceed its daily email limit, using this method results in the following error: system.handledexception: the daily limit for the org would be exceeded by this request.if 3196apex reference guide messaging class the organization doesn’t have permission to send api or mass email, using this method results in the following error: system.noaccessexception: the organization is not permitted to send email. sendemail(emails, allornothing) sends the list of emails instantiated with either singleemailmessage or massemailmessage and returns a list of sendemailresult objects. when org preferences are set to save emailmessage objects and a trigger is defined for emailmessage objects, the trigger is fired for each singleemailmessage individually. the sendemail method can be called 10 times per apex transaction and each method invocation can include up to 100 "to", 25 "cc", and 25 "bcc" recipients. signature public messaging.sendemailresult[] sendemail(messaging.email[] emails, boolean allornothing) parameters emails type: messaging.email[] allornothing type: boolean the optional opt_allornone parameter specifies whether sendemail prevents delivery of all other messages when any of the messages fail due to an error (true), or whether it allows delivery of the messages that don't have errors (false). the default is true. return value type: messaging.sendemailresult[] sendemailmessage(emailmessageids, allornothing) sends draft email messages as defined by the specified email message |
ids and returns a list of sendemailresult objects. signature public messaging.sendemailresult[] sendemailmessage(list<id> emailmessageids, boolean allornothing) parameters emailmessageids type: list<id> allornothing type: boolean return value type: messaging.sendemailresult[] if the emailmessageids parameter is null, the method throws a system.illegalargumentexception exception. 3197apex reference guide messaging class usage the sendemailmessage method assumes that the optional allornothing parameter is always false and ignores the value you set. delivery of all messages is attempted even if some messages fail due to an error. example this example shows how to send a draft email message. it creates a case and a new email message associated with the case. next, the example sends a draft email message and checks the results. before running this example, make sure to replace the email address with a valid address. case c = new case(); insert c; emailmessage e = new emailmessage(); e.parentid = c.id; // set to draft status. // this status is required // for sendemailmessage(). e.status = '5'; e.textbody = 'sample email message.'; e.subject = 'apex sample'; e.toaddress = '[email protected]'; insert e; list<messaging.sendemailresult> results = messaging.sendemailmessage(new id[] { e.id }); system.assertequals(1, results.size()); system.assertequals(true, results[0].success); versioned behavior changes in api version 54.0 and later, a null emailmessageids parameter results in a system.illegalargumentexception exception. in api version 53.0 and earlier, a null emailmessageids parameter results in an error. renderemailtemplate(whoid, whatid, bodies) replaces merge fields in text bodies of email templates with values from salesforce records. returns an array of renderemailtemplatebodyresult objects, each of which corresponds to an element in the supplied array of text bodies. each renderemailtemplatebodyresult provides a success or failure indication, along with either an error code or the rendered text. signature public static list<messaging.renderemailtemplatebodyresult> renderemailtemplate(string whoid, string whatid, list<string> bodies) 3198apex reference guide messaging class parameters whoid type: string the identifier of an object in the database, typically a contact, lead, or user. the database record for that object is read and used in merge field processing. whatid type: string identifies an object in the database like an account or opportunity. the record for that object is read and used in merge field processing. bodies type: list<string> an array of strings that are examined for merge field references. the corresponding data from the object referenced by the whoid or whatid replaces the merge field reference. return value type: list<messaging.renderemailtemplatebodyresult> usage use this method in situations in which you want to dynamically compose blocks of text that are enriched with data from the database. you can then use the the rendered blocks of text to compose and send an email or update a text value in another database record. executing the renderemailtemplate method counts toward the soql governor limit. the number of soql queries that this method consumes is the number of elements in the list of strings passed in the bodies parameter. see also: execution governors and limits renderstoredemailtemplate(templateid, whoid, whatid) renders a text, custom, html, or visualforce email template that exists in the database into an instance of messaging.singleemailmessage. includes all attachment content in the returned email message. signature public static messaging.singleemailmessage renderstoredemailtemplate(string templateid, string whoid, string whatid) parameters templateid type: string an email template that exists in the database, such as text, html, custom, and visualforce templates. whoid type: string the identifier of an object in the database, typically a contact, lead, or user. the database record for that object is read and used in merge field processing. 3199apex reference guide messaging class whatid type: string identifies an object in the database, like an account or opportunity. the record for that object is read and used in merge field processing. return value type |
: messaging.singleemailmessage usage executing the renderstoredemailtemplate method counts toward the soql governor limit as one query. see also: execution governors and limits renderstoredemailtemplate(templateid, whoid, whatid, attachmentretrievaloption) renders a text, custom, html, or visualforce email template that exists in the database into an instance of messaging.singleemailmessage. provides options for including attachment metadata only, attachment metadata and content, or excluding attachments. signature public static messaging.singleemailmessage renderstoredemailtemplate(string templateid, string whoid, string whatid, messaging.attachmentretrievaloption attachmentretrievaloption) parameters templateid type: string an email template that exists in the database, such as text, html, custom, and visualforce templates. whoid type: string the identifier of an object in the database, typically a contact, lead, or user. the database record for that object is read and used in merge field processing. whatid type: string identifies an object in the database, like an account or opportunity. the record for that object is read and used in merge field processing. attachmentretrievaloption type: messaging.attachmentretrievaloption 3200apex reference guide messaging class specifies options for including attachments in the fileattachments property of the returned messaging.singleemailmessage. set to one of the messaging.attachmentretrievaloption values to include attachment metadata only, attachment metadata and content, or to exclude attachments. note: when the attachmentretrievaloption parameter is not set to none, the entityattachments property of messaging.singleemailmessage contains the id of the salesforce content objects to attach (contentversion or document). the fileattachments property contains the ids of attachments, in addition to all the ids in the entityattachments property. as a result, the id values in entityattachments are duplicates of the ids in the fileattachments property. if you call renderstoredemailtemplate() by passing the metadata_with_body option, and send the rendered email message, the email will contain duplicate attachments. before using the returned email message with sendemail(emails, allornothing), you can remove attachments from fileattachments that are duplicated in entityattachments. return value type: messaging.singleemailmessage usage executing the renderstoredemailtemplate method counts toward the soql governor limit as one query. renderstoredemailtemplate(templateid, whoid, whatid, attachmentretrievaloption, updateemailtemplateusage) renders a text, custom, html, or visualforce email template that exists in the database into an instance of messaging.singleemailmessage. provides options for including attachment metadata only, attachment metadata and content, or excluding attachments. signature public static messaging.singleemailmessage renderstoredemailtemplate(string templateid, string whoid, string whatid, messaging.attachmentretrievaloption attachmentretrievaloption, boolean updateemailtemplateusage) parameters templateid type: string an email template that exists in the database, such as text, html, custom, and visualforce templates. whoid type: string the identifier of an object in the database, typically a contact, lead, or user. the database record for that object is read and used in merge field processing. whatid type: string identifies an object in the database, like an account or opportunity. the record for that object is read and used in merge field processing. 3201apex reference guide multistaticresourcecalloutmock class attachmentretrievaloption type: messaging.attachmentretrievaloption specifies options for including attachments in the fileattachments property of the returned messaging.singleemailmessage. set to one of the messaging.attachmentretrievaloption values to include attachment metadata only, attachment metadata and content, or to exclude attachments. note: when the attachmentretrievaloption parameter is not set to none, the entityattachments property of messaging.singleemailmessage contains the id of the salesforce content objects to attach (contentversion or document). the fileattachments property contains the ids of attachments, in addition to all the ids in the entityattachments property. as a result, the id values in entityattachments are duplicates of the ids in the fileattachments property. if you call renderstoredemailtemplate() by passing the metadata_with_b |
ody option, and send the rendered email message, the email will contain duplicate attachments. before using the returned email message with sendemail(emails, allornothing), you can remove attachments from fileattachments that are duplicated in entityattachments. updateemailtemplateusage type: boolean specifies whether the usage field in the emailtemplate record is updated upon successful rendering. return value type: messaging.singleemailmessage usage executing the renderstoredemailtemplate method counts toward the soql governor limit as one query. multistaticresourcecalloutmock class utility class used to specify a fake response using multiple resources for testing http callouts. namespace system usage use the methods in this class to set the response properties for testing http callouts. you can specify a resource for each endpoint. in this section: multistaticresourcecalloutmock constructors multistaticresourcecalloutmock methods multistaticresourcecalloutmock constructors the following are constructors for multistaticresourcecalloutmock. 3202apex reference guide multistaticresourcecalloutmock class in this section: multistaticresourcecalloutmock() creates a new instance of the system.multistaticresourcecalloutmock class. multistaticresourcecalloutmock() creates a new instance of the system.multistaticresourcecalloutmock class. signature public multistaticresourcecalloutmock() multistaticresourcecalloutmock methods the following are methods for multistaticresourcecalloutmock. all are instance methods. in this section: setheader(headername, headervalue) sets the specified header name and value for the fake response. setstaticresource(endpoint, resourcename) sets the specified static resource corresponding to the endpoint. the static resource contains the response body. setstatus(httpstatus) sets the specified http status for the response. setstatuscode(httpstatuscode) sets the specified http status code for the response. setheader(headername, headervalue) sets the specified header name and value for the fake response. signature public void setheader(string headername, string headervalue) parameters headername type: string headervalue type: string return value type: void 3203apex reference guide multistaticresourcecalloutmock class setstaticresource(endpoint, resourcename) sets the specified static resource corresponding to the endpoint. the static resource contains the response body. signature public void setstaticresource(string endpoint, string resourcename) parameters endpoint type: string resourcename type: string return value type: void setstatus(httpstatus) sets the specified http status for the response. signature public void setstatus(string httpstatus) parameters httpstatus type: string return value type: void setstatuscode(httpstatuscode) sets the specified http status code for the response. signature public void setstatuscode(integer httpstatuscode) parameters httpstatuscode type: integer 3204apex reference guide network class return value type: void network class manage experience cloud sites. namespace system in this section: network constructors create an instance of the system.network class. network methods get the default landing page, login page, and self-registration page of a site. asynchronously create site users and records. get the login and logout urls for a site. get a user’s current site. map dashboards and insights reports. network constructors create an instance of the system.network class. the following are constructors for network. in this section: network() creates a new instance of the system.network class. network() creates a new instance of the system.network class. signature public network() network methods get the default landing page, login page, and self-registration page of a site. asynchronously create site users and records. get the login and logout urls for a site. get a user’s current site. map dashboards and insights reports. the following are methods for network. all methods are static. in this section: communitieslanding() returns a page reference to the default landing page for the experience cloud site. this is the first tab of the site. 3205apex reference guide network class createexternaluserasync(user, contact, account) asynchronously creates an experience cloud site user for the given account or contact and associates it with the site. this method processes |
requests in batches and then sends an email with login information to the user. createrecordasync(processtype, mbobject) asynchronously creates case, lead, and custom object records. this method collects record creation requests and processes them in batches. forwardtoauthpage(starturl) returns a page reference to the default login page. starturl is included as a query paremeter for where to redirect after a successful login. getloginurl(networkid) returns the absolute url of the login page used by the experience cloud site. getlogouturl(networkid) returns the absolute url of the logout page used by the experience cloud site. getnetworkid() returns the user’s current experience cloud site. getselfregurl(networkid) returns the absolute url of the self-registration page used by the experience cloud site. loadallpackagedefaultnetworkdashboardsettings() maps the dashboards from the salesforce communities management package onto each experience cloud site’s unconfigured dashboard settings. returns the number of settings it configures. loadallpackagedefaultnetworkpulsesettings() maps the insights reports from the salesforce communities management package onto each experience cloud site’s unconfigured insights settings. returns the number of settings it configures. communitieslanding() returns a page reference to the default landing page for the experience cloud site. this is the first tab of the site. signature public static string communitieslanding() return value type: pagereference usage if digital experiences isn’t enabled for the user’s org or the user is currently in the internal org, returns null. createexternaluserasync(user, contact, account) asynchronously creates an experience cloud site user for the given account or contact and associates it with the site. this method processes requests in batches and then sends an email with login information to the user. 3206apex reference guide network class signature public static string createexternaluserasync(sobject user, sobject contact, sobject account) parameters user type: sobject (optional) information required to create a user. contact type: sobject (optional) the contact you want to associate the user with. account type: sobject the account you want to associate the user with. return value type: string returns the uuid for the site user. createrecordasync(processtype, mbobject) asynchronously creates case, lead, and custom object records. this method collects record creation requests and processes them in batches. signature public static string createrecordasync(string processtype, sobject mbobject) parameters processtype type: string the process you use to create records. mbobject type: sobject the records created for objects. objects must be supported by the high-volume record creation. return value type: string returns the uuid for the record created. 3207apex reference guide network class forwardtoauthpage(starturl) returns a page reference to the default login page. starturl is included as a query paremeter for where to redirect after a successful login. signature public static pagereference forwardtoauthpage(string starturl) parameters starturl type: string return value type: pagereference usage if digital experiences isn’t enabled for the user’s org or the user is currently in the internal org, returns null. getloginurl(networkid) returns the absolute url of the login page used by the experience cloud site. signature public static string getloginurl(string networkid) parameters networkid type: string the id of the experience cloud site you’re retrieving this information for. return value type: string usage returns the full url for the lightning platform or experience builder page used as the login page in the experience cloud site. getlogouturl(networkid) returns the absolute url of the logout page used by the experience cloud site. signature public static string getlogouturl(string networkid) 3208apex reference guide network class parameters networkid type: string the id of the experience cloud site you’re retrieving this information for. return value type: string usage returns the full url for the lightning platform page, experience builder page, or web page used as the logout page in the experience cloud site. getnetworkid() returns the user’s current experience cloud site. signature public static string getnetworkid() return value type: string usage if digital experiences isn |
’t enabled for the user’s org or the user is currently in the internal org, returns null. getselfregurl(networkid) returns the absolute url of the self-registration page used by the experience cloud site. signature public static string getselfregurl(string networkid) parameters networkid type: string the id of the experience cloud site you’re retrieving this information for. return value type: string 3209apex reference guide orglimit class usage returns the full url for the lightning platform or experience builder page used as the self-registration page in the experience cloud site. loadallpackagedefaultnetworkdashboardsettings() maps the dashboards from the salesforce communities management package onto each experience cloud site’s unconfigured dashboard settings. returns the number of settings it configures. signature public static integer loadallpackagedefaultnetworkdashboardsettings() return value type: integer usage if digital experiences is enabled, and the salesforce communities management package is installed, maps the dashboards provided in the package onto each experience cloud site’s unconfigured dashboard settings. returns the number of settings it configures. this method is invoked automatically during site creation and package installation, but isn’t typically invoked manually. if digital experiences isn’t enabled for the user’s org or the user is in the internal org, returns 0. loadallpackagedefaultnetworkpulsesettings() maps the insights reports from the salesforce communities management package onto each experience cloud site’s unconfigured insights settings. returns the number of settings it configures. signature public static integer loadallpackagedefaultnetworkpulsesettings() return value type: integer usage if digital experiences is enabled, and the salesforce communities management package is installed, maps the insights reports provided in the package onto each experience cloud site’s unconfigured insights settings. returns the number of settings it configures. this method is invoked automatically during site creation and package installation, but isn’t typically invoked manually. if digital experiences isn’t enabled for the user’s org or the user is in the internal org, returns 0. orglimit class contains methods that provide the name, maximum value, and current value of an org limit. 3210apex reference guide orglimit class namespace system usage use the system.orglimits getall and getmap methods to obtain either a list or a map of all your org limits. to get details on each limit, use instance methods from system.orglimit. for comparison, the limits class returns apex governor limits and not salesforce api limits. note: limit values are updated asynchronously, in near-real-time. in this section: orglimit methods orglimit methods the following are methods for orglimit. in this section: getlimit() returns the maximum allowed limit value. getname() returns the limit’s name. getvalue() returns the limit usage value. tostring() returns the string representation of the org limit. getlimit() returns the maximum allowed limit value. signature public integer getlimit() return value type: integer example list<system.orglimit> limits = orglimits.getall(); for (system.orglimit alimit: limits) { system.debug('limit: ' + alimit.getname()); 3211apex reference guide orglimit class system.debug('max limit is: ' + alimit.getlimit()); } getname() returns the limit’s name. signature public string getname() return value type: string example list<system.orglimit> limits = orglimits.getall(); for (system.orglimit alimit: limits) { system.debug('limit: ' + alimit.getname()); system.debug('max limit is: ' + alimit.getlimit()); } getvalue() returns the limit usage value. signature public integer getvalue() return value type: integer example list<system.orglimit> limits = orglimits.getall(); for (system.orglimit alimit: limits) { system.debug('limit: ' + alimit.getname()); system.debug('usage value is: ' + alimit.getvalue()); } tostring() returns the string representation of the org limit. signature public string tostring() 3212apex reference guide orglimits class return value type |
: string string denoting the name, current consumption, and maximum value of the org limit. for example: orglimit[dailybulkapibatches: consumed 25 of 15000] orglimits class contains methods that provide a list or map of all orglimit instances for salesforce your org, such as soap api requests, bulk api requests, and streaming api limits. namespace system usage use the system.orglimits getall and getmap methods to obtain either a list or a map of all your org limits. to get details on each limit, use instance methods from system.orglimit. for comparison, the limits class returns apex governor limits and not salesforce api limits. note: limit values are updated asynchronously, in near-real-time. in this section: orglimits methods see also: rest api developer guide: limits orglimits methods the following are methods for orglimits. in this section: getall() returns a list of orglimit instances. getmap() returns a map of all orglimit instances with the limit name as key. getall() returns a list of orglimit instances. 3213apex reference guide pagereference class signature public static list<system.orglimit> getall() return value type: list<system.orglimit> getmap() returns a map of all orglimit instances with the limit name as key. signature public static map<string,system.orglimit> getmap() return value type: map<string,system.orglimit> example map<string,system.orglimit> limitsmap = orglimits.getmap(); system.orglimit apirequestslimit = limitsmap.get('dailyapirequests'); system.debug('limit name: ' + apirequestslimit.getname()); system.debug('usage value: ' + apirequestslimit.getvalue()); system.debug('maximum limit: ' + apirequestslimit.getlimit()); pagereference class a pagereference is a reference to an instantiation of a page. among other attributes, pagereferences consist of a url and a set of query parameter names and values. namespace system use a pagereference object: • to view or set query string parameters and values for a page • to navigate the user to a different page as the result of an action method instantiation in a custom controller or controller extension, you can refer to or instantiate a pagereference in one of the following ways: 3214apex reference guide pagereference class • page.existingpagename refers to a pagereference for a visualforce page that has already been saved in your organization. by referring to a page in this way, the platform recognizes that this controller or controller extension is dependent on the existence of the specified page and will prevent the page from being deleted while the controller or extension exists. • pagereference pageref = new pagereference('partialurl'); creates a pagereference to any page that is hosted on the lightning platform. for example, setting 'partialurl' to '/apex/helloworld' refers to the visualforce page located at http://mysalesforceinstance/apex/helloworld. likewise, setting 'partialurl' to '/' + 'recordid' refers to the detail page for the specified record. this syntax is less preferable for referencing other visualforce pages than page.existingpagename because the pagereference is constructed at runtime, rather than referenced at compile time. runtime references are not available to the referential integrity system. consequently, the platform doesn't recognize that this controller or controller extension is dependent on the existence of the specified page and won't issue an error message to prevent user deletion of the page. • pagereference pageref = new pagereference('fullurl'); creates a pagereference for an external url. for example: pagereference pageref = new pagereference('http://www.google.com'); you can also instantiate a pagereference object for the current page with the currentpage apexpages method. for example: pagereference pageref = apexpages.currentpage(); request headers the following table is a non-exhaustive list of headers that are set on requests. header description host the host name requested in the request url. this header is always set on lightning platform site requests and my domain requests. this header is optional on other requests when http/1.0 is used instead of http/1.1. referer the url that is either included or linked to the current request's url. this header is optional. user |
-agent the name, version, and extension support of the program that initiated this request, such as a web browser. this header is optional and can be overridden in most browsers to be a different value. therefore, this header should not be relied upon. ciphersuite if this header exists and has a non-blank value, this means that the request is using https. otherwise, the request is using http. the contents of a non-blank value are not defined by this api, and can be changed without notice. x-salesforce-sip the source ip address of the request. this header is always set on http and https requests that are initiated outside of salesforce's data centers. note: if a request passes through a content delivery network (cdn) or proxy server, the source ip address might be altered, and no longer the original client ip address. 3215apex reference guide pagereference class header description x-salesforce-forwarded-to the fully qualified domain name of the salesforce instance that is handling this request. this header is always set on http and https requests that are initiated outside of salesforce's data centers. example: retrieving query string parameters the following example shows how to use a pagereference object to retrieve a query string parameter in the current page url. in this example, the getaccount method references the id query string parameter: public with sharing class mycontroller { public account getaccount() { return [select id, name from account with security_enforced where id = :apexpages.currentpage().getparameters().get('id')]; } } the following page markup calls the getaccount method from the controller above: <apex:page controller="mycontroller"> <apex:pageblock title="retrieving query string parameters"> you are viewing the {!account.name} account. </apex:pageblock> </apex:page> note: for this example to render properly, you must associate the visualforce page with a valid account record in the url. for example, if 001d000000irt53 is the account id, the resulting url should be: https://salesforce_instance/apex/myfirstpage?id=001d000000irt53 the getaccount method uses an embedded soql query to return the account specified by the id parameter in the url of the page. to access id, the getaccount method uses the apexpages namespace: • first the currentpage method returns the pagereference instance for the current page. pagereference returns a reference to a visualforce page, including its query string parameters. • using the page reference, use the getparameters method to return a map of the specified query string parameter names and values. • then a call to the get method specifying id returns the value of the id parameter itself. example: navigating to a new page as the result of an action method any action method in a custom controller or controller extension can return a pagereference object as the result of the method. if the redirect attribute on the pagereference is set to true, the user navigates to the url specified by the pagereference. the following example shows how this can be implemented with a save method. in this example, the pagereference returned by the save method redirects the user to the detail page for the account record that was just saved: public class mysecondcontroller { account account; public account getaccount() { if(account == null) account = new account(); return account; 3216apex reference guide pagereference class } public pagereference save() { // add the account to the database. insert account; // send the user to the detail page for the new account. pagereference acctpage = new apexpages.standardcontroller(account).view(); acctpage.setredirect(true); return acctpage; } } the following page markup calls the save method from the controller above. when a user clicks save, he or she is redirected to the detail page for the account just created: <apex:page controller="mysecondcontroller" tabstyle="account"> <apex:sectionheader title="new account edit page" /> <apex:form> <apex:pageblock title="create a new account"> <apex:pageblockbuttons location="bottom"> <apex:commandbutton action="{!save}" value="save"/> </apex:pageblockbuttons> <apex:pageblocksection title="account information"> <apex:inputfield id="accountname" value="{!account.name}"/> <apex:inputfield id=" |
accountsite" value="{!account.site}"/> </apex:pageblocksection> </apex:pageblock> </apex:form> </apex:page> example: redirect users to a replacement experience cloud site the following example shows how to redirect a user attempting to access a retired feedback site to a self-service help site. if the redirect attribute is set to true on the pagereference for the feedback site, the user navigates to the url specified by the pagereference. the redirectcode attribute defines the redirection type for search engine optimization in public experience cloud sites. public class redirectcontroller { // redirect users to the self-service help site public pagereference redirect() { final pagereference target = new pagereference(site.getbasesecureurl() + '/sitelogin'); target.setredirect(true); // this is a permanent redirection target.setredirectcode(301); return target; } } the following example shows how to call the redirectcontroller class from the retired site page. <apex:page controller="redirectcontroller" action="{!redirect}"/> 3217apex reference guide pagereference class in this section: pagereference constructors pagereference methods pagereference constructors the following are constructors for pagereference. in this section: pagereference(partialurl) creates a new instance of the pagereference class using the specified url. pagereference(record) generate a new instance of the pagereference class for the specified sobject record. pagereference(partialurl) creates a new instance of the pagereference class using the specified url. signature public pagereference(string partialurl) parameters partialurl type: string the partial url of a page hosted on the lightning platform or a full external url. the following are some examples of the partialurl parameter values: • /apex/helloworld: refers to the visualforce page located at http://mydomainname-packagename.vf.force.com/apex/helloworld. • /recordid: refers to the detail page of a specified record. • http://www.google.com: refers to an external url. pagereference(record) generate a new instance of the pagereference class for the specified sobject record. signature public pagereference(sobject record) parameters record type: sobject 3218apex reference guide pagereference class the sobject record that references the apexpage. the reference must be an apexpage. see also: visualforce developer guide: apex:page soap api developer guide: apexpage pagereference methods the following are methods for pagereference. all are instance methods. in this section: forresource(resourcename, path) create a pagereference for nested content inside a zip static resource, by name and path. forresource(resourcename) create a pagereference for a static resource, by name. getanchor() returns the name of the anchor referenced in the page’s url. that is, the part of the url after the hashtag (#). getcontent() returns the output of the page, as displayed to a user in a web browser. getcontentaspdf() returns the page in pdf, regardless of the <apex:page> component’s renderas attribute. getcookies() returns a map of cookie names and cookie objects, where the key is a string of the cookie name and the the value contains the cookie object with that name. getheaders() returns a map of the request headers, where the key string contains the name of the header, and the value string contains the value of the header. getparameters() returns a map of the query string parameters for the pagereference; both post and get parameters are included. the key string contains the name of the parameter, while the value string contains the value of the parameter. getredirect() returns the current value of the pagereference object's redirect attribute. getredirectcode() returns the http redirect code used when getredirect() is set to true for the pagereference object. geturl() returns the relative url associated with the pagereference when it was originally defined, including any query string parameters and anchors. setanchor(anchor) sets the url’s anchor reference to the specified string. setcookies(cookies) creates a list of cookie objects. used in conjunction with the cookie class. 3219apex reference guide pagereference class setredirect(redirect) sets the value of the pagereference |
object's redirect attribute. if set to true, a redirect is performed through a client side redirect. setredirectcode(redirectcode) sets the http redirect code to use for the pagereference object when setredirect(redirect) is set to true. forresource(resourcename, path) create a pagereference for nested content inside a zip static resource, by name and path. signature public static system.pagereference forresource(string resourcename, string path) parameters resourcename type: string the resource name path type: string the resource path return value type: system.pagereference forresource(resourcename) create a pagereference for a static resource, by name. signature public static system.pagereference forresource(string resourcename) parameters resourcename type: string the resource name return value type: system.pagereference getanchor() returns the name of the anchor referenced in the page’s url. that is, the part of the url after the hashtag (#). 3220apex reference guide pagereference class signature public string getanchor() return value type: string note: instances of pagereference returned by apexpages.currentpage() have a null anchor attribute, because url fragments are not sent to the salesforce server during a request. getcontent() returns the output of the page, as displayed to a user in a web browser. signature public blob getcontent() return value type: blob usage the content of the returned blob depends on how the page is rendered. if the page is rendered as a pdf file, it returns the pdf document. if the page is not rendered as pdf, it returns html. to access the content of the returned html as a string, use the tostring blob method. note: if you use getcontent in a test method, the test method fails. getcontent is treated as a callout in api version 34.0 and later. this method can’t be used in: • triggers • test methods • apex email services if the visualforce page has an error, an executionexception is thrown. getcontentaspdf() returns the page in pdf, regardless of the <apex:page> component’s renderas attribute. signature public blob getcontentaspdf() return value type: blob 3221apex reference guide pagereference class usage note: if you use getcontentaspdf in a test method, the test method fails. getcontentaspdf is treated as a callout in api version 34.0 and later. this method can’t be used in: • triggers • test methods • apex email services getcookies() returns a map of cookie names and cookie objects, where the key is a string of the cookie name and the the value contains the cookie object with that name. signature public map<string, system.cookie> getcookies() return value type: map<string, system.cookie> usage used in conjunction with the cookie class. only returns cookies with the “apex__” prefix set by the setcookies method. getheaders() returns a map of the request headers, where the key string contains the name of the header, and the value string contains the value of the header. signature public map<string, string> getheaders() return value type: map<string, string> usage this map can be modified and remains in scope for the pagereference object. for instance, you could do: pagereference.getheaders().put('date', '9/9/99'); for a description of request headers, see request headers. getparameters() returns a map of the query string parameters for the pagereference; both post and get parameters are included. the key string contains the name of the parameter, while the value string contains the value of the parameter. 3222apex reference guide pagereference class signature public map<string, string> getparameters() return value type: map<string, string> usage this map can be modified and remains in scope for the pagereference object. for instance, you could do: pagereference.getparameters().put('id', myid); parameter keys are case-insensitive. for example: system.assert( apexpages.currentpage().getparameters().get('myparamname') == apexpages.currentpage().getparameters().get('myparamname')); getredirect() returns |
the current value of the pagereference object's redirect attribute. signature public boolean getredirect() return value type: boolean usage note that if the url of the pagereference object is set to a website outside of the salesforce.com domain, the redirect always occurs, regardless of whether the redirect attribute is set to true or false. getredirectcode() returns the http redirect code used when getredirect() is set to true for the pagereference object. signature public integer getredirectcode() return value type: integer possible values: • 0 — redirect using the default redirect action for this pagereference. typically a javascript-based redirection or http 302. 3223apex reference guide pagereference class note: site urlrewirter interface implementations pointing to a pagereference with a redirectcode of 0 are not redirected. • 301 — moved permanently. redirect users by sending an http get request to the target location. includes instructions to update any references to the requested url with the target location. • 302 — moved temporarily. redirect users by sending an http get request to the target location. because the redirection is temporary, it doesn’t include update instructions. • 303 — see other. redirect users by sending an http get request to the target location. not commonly used. useful when the client sends a post request and you want the client to call the new web page using a get request instead of a post request. • 307 — temporary redirect. send the same http request, regardless of the http method, to the target location. because the redirection is temporary, it doesn’t include update instructions. • 308 — permanent redirect. send the same http request, regardless of the http method, to the target location. includes instructions to update any references to the requested url with the target location. geturl() returns the relative url associated with the pagereference when it was originally defined, including any query string parameters and anchors. signature public string geturl() return value type: string setanchor(anchor) sets the url’s anchor reference to the specified string. signature public system.pagereference setanchor(string anchor) parameters anchor type: string return value type: system.pagereference setcookies(cookies) creates a list of cookie objects. used in conjunction with the cookie class. 3224apex reference guide pagereference class signature public void setcookies(cookie[] cookies) parameters cookies type: system.cookie[] return value type: void usage important: • cookie names and values set in apex are url encoded, that is, characters such as @ are replaced with a percent sign and their hexadecimal representation. • the setcookies method adds the prefix “apex__” to the cookie names. • setting a cookie's value to null sends a cookie with an empty string value instead of setting an expired attribute. • after you create a cookie, the properties of the cookie can't be changed. • be careful when storing sensitive information in cookies. pages are cached regardless of a cookie value. if you use a cookie value to generate dynamic content, you should disable page caching. for more information, see configure site caching in salesforce help. setredirect(redirect) sets the value of the pagereference object's redirect attribute. if set to true, a redirect is performed through a client side redirect. signature public system.pagereference setredirect(boolean redirect) parameters redirect type: boolean return value type: system.pagereference usage this type of redirect performs an http get request, and flushes the view state, which uses post. if set to false, the redirect is a server-side forward that preserves the view state if and only if the target page uses the same controller and contains the proper subset of extensions used by the source page. 3225apex reference guide packaging class note that if the url of the pagereference object is set to a website outside of the salesforce.com domain, or to a page with a different controller or controller extension, the redirect always occurs, regardless of whether the redirect attribute is set to true or false. setredirectcode(redirectcode) sets the http redirect code to use for the pagereference object when setredirect(redirect) is set to true. signature public system.pagereference setredirectcode(integer redirectcode) parameters redirectcode type: integer valid values: |
• 0 — redirect using the default redirect action for this pagereference. typically a javascript-based redirection or http 302. note: site urlrewirter interface implementations pointing to a pagereference with a redirectcode of 0 are not redirected. • 301 — moved permanently. redirect users by sending an http get request to the target location. includes instructions to update any references to the requested url with the target location. • 302 — moved temporarily. redirect users by sending an http get request to the target location. because the redirection is temporary, it doesn’t include update instructions. • 303 — see other. redirect users by sending an http get request to the target location. not commonly used. useful when the client sends a post request and you want the client to call the new web page using a get request instead of a post request. • 307 — temporary redirect. send the same http request, regardless of the http method, to the target location. because the redirection is temporary, it doesn’t include update instructions. • 308 — permanent redirect. send the same http request, regardless of the http method, to the target location. includes instructions to update any references to the requested url with the target location. if the redirect code contains an invalid integer, an error message is displayed when pagereference is used by salesforce for redirection. return value type: system.pagereference packaging class contains a method for obtaining information about managed and unlocked packages. namespace system 3226apex reference guide pattern class usage in the context of a package, use the getcurrentpackageid method to retrieve the packageid. in this section: packaging methods packaging methods the following are methods for packaging. in this section: getcurrentpackageid() returns the context packageid in managed and unlocked packages. getcurrentpackageid() returns the context packageid in managed and unlocked packages. signature public string getcurrentpackageid() return value type: string usage for managed packages, this method can be combined with iscurrentuserlicensedforpackage(packageid) to retrieve the packageid at runtime. then, use packageid to confirm that the contextual user is licensed to use that managed package. pattern class represents a compiled representation of a regular expression. namespace system pattern methods the following are methods for pattern. in this section: compile(regexp) compiles the regular expression into a pattern object. 3227apex reference guide pattern class matcher(stringtomatch) creates a matcher object that matches the input string stringtomatch against this pattern object. matches(regexp, stringtomatch) compiles the regular expression regexp and tries to match it against the specified string. this method returns true if the specified string matches the regular expression, false otherwise. pattern() returns the regular expression from which this pattern object was compiled. quote(yourstring) returns a string that can be used to create a pattern that matches the string yourstring as if it were a literal pattern. split(regexp) returns a list that contains each substring of the string that matches this pattern. split(regexp, limit) returns a list that contains each substring of the string that is terminated either by the regular expression regexp that matches this pattern, or by the end of the string. compile(regexp) compiles the regular expression into a pattern object. signature public static pattern compile(string regexp) parameters regexp type: string return value type: system.pattern matcher(stringtomatch) creates a matcher object that matches the input string stringtomatch against this pattern object. signature public matcher matcher(string stringtomatch) parameters stringtomatch type: string return value type: matcher 3228apex reference guide pattern class matches(regexp, stringtomatch) compiles the regular expression regexp and tries to match it against the specified string. this method returns true if the specified string matches the regular expression, false otherwise. signature public static boolean matches(string regexp, string stringtomatch) parameters regexp type: string stringtomatch type: string return value type: boolean usage if a pattern is to be used multiple times, compiling it once and reusing it is more efficient than invoking this method each time. example note that the following code example: pattern.matches(regexp, input); produces the same result as this code example: pattern |
.compile(regex). matcher(input).matches(); pattern() returns the regular expression from which this pattern object was compiled. signature public string pattern() return value type: string quote(yourstring) returns a string that can be used to create a pattern that matches the string yourstring as if it were a literal pattern. 3229apex reference guide pattern class signature public static string quote(string yourstring) parameters yourstring type: string return value type: string usage metacharacters (such as $ or ^) and escape sequences in the input string are treated as literal characters with no special meaning. split(regexp) returns a list that contains each substring of the string that matches this pattern. 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 the substrings are placed in the list in the order in which they occur in the string. if regexp does not match the pattern, the resulting list has just one element containing the original string. split(regexp, limit) returns a list that contains each substring of the string that is terminated either by the regular expression regexp that matches this pattern, or by the end of the string. signature public string[] split(string regexp, integer limit) 3230apex reference guide queueable interface parameters regexp type: string limit type: integer (optional) 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. • 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. 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. queueable interface enables the asynchronous execution of apex jobs that can be monitored. namespace system usage to execute apex as an asynchronous job, implement the queueable interface and add the processing logic in your implementation of the execute method. to implement the queueable interface, you must first declare a class with the implements keyword as follows: public class myqueueableclass implements queueable { next, your class must provide an implementation for the following method: public void execute(queueablecontext context) { // your code here } your class and method implementation must be declared as public or global. to submit your class for asynchronous execution, call the system.enqueuejob by passing it an instance of your class implementation of the queueable interface as follows: id jobid = system.enqueuejob(new myqueueableclass()); 3231apex reference guide queueable interface in this section: queueable methods queueable example implementation see also: apex developer guide: queueable apex queueable methods the following are methods for queueable. in this section: execute(context) executes the queueable job. execute(context) executes the queueable job. signature public void execute(queueablecontext context) parameters context type: queueablecontext contains the job id. return value type: void queueable example implementation this example is an implementation of the queueable interface. the execute method in this example inserts a new account. public class asyncexecutionexample implements queueable { public void execute(queueablecontext context) { account a = new account(name='acme',phone='(415) 555-1212'); insert a; } } to add this class as a job on the queue, call this method: id jobid = system.enqueuejob(new asyncexecutionexample()); 3232 |
apex reference guide queueablecontext interface after you submit your queueable class for execution, the job is added to the queue and will be processed when system resources become available. you can monitor the status of your job programmatically by querying asyncapexjob or through the user interface in setup by entering apex jobs in the quick find box, then selecting apex jobs. to query information about your submitted job, perform a soql query on asyncapexjob by filtering on the job id that the system.enqueuejob method returns. this example uses the jobid variable that was obtained in the previous example. asyncapexjob jobinfo = [select status,numberoferrors from asyncapexjob where id=:jobid]; similar to future jobs, queueable jobs don’t process batches, and so the number of processed batches and the number of total batches are always zero. testing queueable jobs this example shows how to test the execution of a queueable job in a test method. a queueable job is an asynchronous process. to ensure that this process runs within the test method, the job is submitted to the queue between the test.starttest and test.stoptest block. the system executes all asynchronous processes started in a test method synchronously after the test.stoptest statement. next, the test method verifies the results of the queueable job by querying the account that the job created. @istest public class asyncexecutionexampletest { static testmethod void test1() { // starttest/stoptest block to force async processes // to run in the test. test.starttest(); system.enqueuejob(new asyncexecutionexample()); test.stoptest(); // validate that the job has run // by verifying that the record was created. // this query returns only the account created in test context by the // queueable class method. account acct = [select name,phone from account where name='acme' limit 1]; system.assertnotequals(null, acct); system.assertequals('(415) 555-1212', acct.phone); } } note: the id of a queueable apex job isn’t returned in test context—system.enqueuejob returns null in a running test. queueablecontext interface represents the parameter type of the execute() method in a class that implements the queueable interface and contains the job id. this interface is implemented internally by apex. namespace system 3233apex reference guide quickaction class queueablecontext methods the following are methods for queueablecontext. in this section: getjobid() returns the id of the submitted job that uses the queueable interface. getjobid() returns the id of the submitted job that uses the queueable interface. signature public id getjobid() return value type: id the id of the submitted job. quickaction class use apex to request and process actions on objects that allow custom fields, on objects that appear in a chatter feed, or on objects that are available globally. namespace system example in this sample, the trigger determines if the new contacts to be inserted are created by a quick action. if so, it sets the wherefrom__c custom field to a value that depends on whether the quick action is global or local to the contact. otherwise, if the inserted contacts don’t originate from a quick action, the wherefrom__c field is set to 'noaction'. trigger acctrig2 on contact (before insert) { for (contact c : trigger.new) { if (c.getquickactionname() == quickaction.createcontact) { c.wherefrom__c = 'globaactionl'; } else if (c.getquickactionname() == schema.account.quickaction.createcontact) { c.wherefrom__c = 'accountaction'; } else if (c.getquickactionname() == null) { c.wherefrom__c = 'noaction'; } else { system.assert(false); } } } 3234apex reference guide quickaction class this sample performs a global action—quickaction.createcontact–on the passed-in contact object. public id globalcreate(contact c) { quickaction.quickactionrequest req = new quickaction.quickactionrequest(); req.quickactionname = quickaction.createcontact; req.record = c; quickaction.quickactionresult res = quickaction.performquickaction(req); return c.id |
; } see also: quickactionrequest class quickactionresult class quickaction methods the following are methods for quickaction. all methods are static. in this section: describeavailablequickactions(parenttype) returns metadata information for the available quick actions of the provided parent object. describeavailablequickactions(sobjectnames) returns the metadata information for the provided quick actions. performquickaction(quickactionrequest) performs the quick action specified in the quick action request and returns the action result. performquickaction(quickactionrequest, allornothing) performs the quick action specified in the quick action request with the option for partial success, and returns the result. performquickactions(quickactionrequests) performs the quick actions specified in the quick action request list and returns action results. performquickactions(quickactionrequests, allornothing) performs the quick actions specified in the quick action request list with the option for partial success, and returns action results. describeavailablequickactions(parenttype) returns metadata information for the available quick actions of the provided parent object. signature public static list<quickaction.describeavailablequickactionresult> describeavailablequickactions(string parenttype) parameters parenttype type: string 3235apex reference guide quickaction class the parent object type. this can be an object type name ('account') or 'global' (meaning that this method is called at a global level and not an entity level). return value type: list<quickaction.describeavailablequickactionresult> the metadata information for the available quick actions of the parent object. example // called for account entity. list<quickaction.describeavailablequickactionresult> result1 = quickaction.describeavailablequickactions('account'); // called at global level, not entity level. list<quickaction.describeavailablequickactionresult> result2 = quickaction.describeavailablequickactions('global'); describeavailablequickactions(sobjectnames) returns the metadata information for the provided quick actions. signature public static list<quickaction.describequickactionresult> describeavailablequickactions(list<string> sobjectnames) parameters sobjectnames type: list<string> the names of the quick actions. the quick action name can contain the entity name if it is at the entity level ('account.quickcreatecontact'), or 'global' if used for the action at the global level ('global.createnewcontact'). return value type: list<quickaction.describequickactionresult> the metadata information for the provided quick actions. example // first 3 parameter values are for actions at the entity level. // last parameter is for an action at the global level. list<quickaction.describequickactionresult> result = quickaction.describequickactions(new list<string> { 'account.quickcreatecontact', 'opportunity.update1', 'contact.create1', 'global.createnewcontact' }); 3236apex reference guide quickaction class performquickaction(quickactionrequest) performs the quick action specified in the quick action request and returns the action result. signature public static quickaction.quickactionresult performquickaction(quickaction.quickactionrequest quickactionrequest) parameters quickactionrequest type: quickaction.quickactionrequest return value type: quickaction.quickactionresult performquickaction(quickactionrequest, allornothing) performs the quick action specified in the quick action request with the option for partial success, and returns the result. signature public static quickaction.quickactionresult performquickaction(quickaction.quickactionrequest quickactionrequest, boolean allornothing) parameters quickactionrequest type: quickaction.quickactionrequest allornothing type: boolean specifies whether this operation allows partial success. if you specify false for this argument and a record fails, the remainder of the dml operation can still succeed. this method returns a result object that can be used to verify which records succeeded, which failed, and why. return value type: quickaction.quickactionresult performquickactions(quickactionrequests) performs the quick actions specified in the quick action request list and returns action results. signature public static list<quickaction.quickactionresult> performquickactions(list<quickaction.quickactionrequest> quickactionrequests) 3237apex reference guide quiddity enum parameters |
quickactionrequests type: list<quickaction.quickactionrequest> return value type: list<quickaction.quickactionresult> performquickactions(quickactionrequests, allornothing) performs the quick actions specified in the quick action request list with the option for partial success, and returns action results. signature public static list<quickaction.quickactionresult> performquickactions(list<quickaction.quickactionrequest> quickactionrequests, boolean allornothing) parameters quickactionrequests type: list<quickaction.quickactionrequest> allornothing type: boolean specifies whether this operation allows partial success. if you specify false for this argument and a record fails, the remainder of the dml operation can still succeed. this method returns a result object that can be used to verify which records succeeded, which failed, and why. return value type: list<quickaction.quickactionresult> quiddity enum specifies a quiddity value used by the methods in the system.request class enum values the following are the values of the system.quiddity enum. value description anonymous execution event is an anonymous apex block. aura execution event is an aura component. batch_acs execution event is an api query cursor driven batch apex. batch_apex execution event is a batch apex job. 3238apex reference guide remoteobjectcontroller value description batch_chunk_parallel execution event is chunks of a batch apex job running in parallel. batch_chunk_serial execution event is chunks of a batch apex job running in serial. bulk_api execution event is a bulk api request. commerce_integration execution event is an apex integration for b2b commerce. discoverable_login execution event is login discoverable login page used by external users to log in to an experience cloud site. function_callback execution event is a callback function. future execution event is a future method. inbound_email_service execution event is an apex inbound email service. invocable_action execution event is an invocable action. iot execution event is a salesforce iot apex integration service. platform_event_publish_callback execution event is an apex publish callback for platform events. post_install_script execution event is a managed package install or upgrade. queueable execution event is a queueable apex operation. quick_action execution event is a quick action. remote_action execution event is a remote action. rest execution event is an apex restful web service. runtest_async execution event is apex tests running asynchronously. runtest_deploy execution event is apex tests run during deployment. runtest_sync execution event is apex tests running synchronously. scheduled execution event is a scheduled apex job. soap execution event is an apex soap web service. synchronous execution event is a synchronous apex operation. transaction_finalizer_queueable execution event is a queueable job with transaction finalizers attached. vf execution event is triggered by a visualforce page. remoteobjectcontroller use remoteobjectcontroller to access the standard visualforce remote objects operations in your remote objects override methods. 3239apex reference guide remoteobjectcontroller namespace system usage remoteobjectcontroller is supported only for use within remote objects methods. see overriding default remote objects operations in the visualforce developer’s guide for examples of how to use remoteobjectcontroller with your visualforce pages. remoteobjectcontroller methods the following are methods for remoteobjectcontroller. all methods are static. in this section: create(type, fields) create a record in the database. del(type, recordids) delete records from the database. retrieve(type, fields, criteria) retrieve records from the database. updat(type, recordids, fields) update records in the database. create(type, fields) create a record in the database. signature public static map<string,object> create(string type, map<string,object> fields) parameters type type: string the sobject type on which create is being called. fields type: map<string,object> the fields and values to set on the new record. return value type: map |
<string,object> the return value is a map that represents the result of the remote objects operation. what is returned depends on the results of the call. 3240apex reference guide remoteobjectcontroller success a map that contains a single element with the id of the record created. for example, { id: 'recordid' }. failure a map that contains a single element with the error message for the overall operation. for example, { error: 'errormessage' }. del(type, recordids) delete records from the database. signature public static map<string,object> del(string type, list<string> recordids) parameters type type: string the sobject type on which delete is being called. recordids type: list<string> the ids of the records to be deleted. return value type: map<string,object> the return value is a map that represents the result of the remote objects operation. what is returned depends on how the method was called and the results of the call. single delete—success a map that contains a single element with the id of the record that was deleted. for example, { id: 'recordid' }. batch delete—success a map that contains a single element, an array of map<string,object> elements. each element contains the id of a record that was deleted and an array of errors, if there were any, for that record’s individual delete. for example, { results: [ { id: 'recordid', errors: ['errormessage', ...]}, ...] }. single and batch delete—failure a map that contains a single element with the error message for the overall operation. for example, { error: 'errormessage' }. retrieve(type, fields, criteria) retrieve records from the database. signature public static map<string,object> retrieve(string type, list<string> fields, map<string,object> criteria) 3241apex reference guide remoteobjectcontroller parameters type type: string the sobject type on which retrieve is being called. fields type: list<string> the fields to retrieve for each record. criteria type: map<string,object> the criteria to use when performing the query. return value type: map<string,object> the return value is a map that represents the result of the remote objects operation. what is returned depends on the results of the call. success a map that contains the following elements. • records: an array of records that match the query conditions. • type: a string that indicates the type of the sobject that was retrieved. • size: the number of records in the response. failure a map that contains a single element with the error message for the overall operation. for example, { error: 'errormessage' }. updat(type, recordids, fields) update records in the database. signature public static map<string,object> updat(string type, list<string> recordids, map<string,object> fields) parameters type type: string the sobject type on which update is being called. recordids type: list<string> the ids of the records to be updated. fields type: map<string,object> 3242apex reference guide request class the fields to update, and the value to update each field with. return value type: map<string,object> the return value is a map that represents the result of the remote objects operation. what is returned depends on how the method was called and the results of the call. single update—success a map that contains a single element with the id of the record that was updated. for example, { id: 'recordid' }. batch update—success a map that contains a single element, an array of map<string,object> elements. each element contains the id of the record updated and an array of errors, if there were any, for that record’s individual update. for example, { results: [ { id: 'recordid', errors: ['errormessage', ...]}, ...] }. single and batch update—failure a map that contains a single element with the error message for the overall operation. for example, { error: 'errormessage' }. request class contains methods to obtain the request id and quiddity value of the current salesforce request. namespace system usage use the request class to detect the current apex context at runtime. the |
methods in the request class obtain a unique request id and the quiddity value that represent the current apex execution type. these values can also be used to correlate with debug and event logs: • the request id is universally unique and present in the debug logs that are triggered by the request. • the request id and quiddity values are the same as in the event log files of the apex execution event type used in event monitoring. example this example code shows how to obtain current apex code context by retrieving the request id and quiddity value of the current request. //get info about the current request request reqinfo = request.getcurrent(); //get the identifier for this request, which is universally unique //same as requestid in splunk or request_id in event monitoring string currentrequestid = reqinfo.getrequestid(); //enum representing how apex is running. e.g. bulk_api vs lightning quiddity currenttype = reqinfo.getquiddity(); //use this with a switch statement, //instead of checking system.isfuture() || system.isqueueable() || ... 3243apex reference guide request class in this section: request methods request methods the following are methods for request. in this section: getcurrent() returns the current request object that contains the request id and quiddity value. getquiddity() returns the quiddity value of the current request object. getrequestid() returns the request id of the current request object. getcurrent() returns the current request object that contains the request id and quiddity value. signature public static system.request getcurrent() return value type: system.request getquiddity() returns the quiddity value of the current request object. signature public system.quiddity getquiddity() return value type: system.quiddity uses the values from the quiddity enum. this value identifies the type of execution event associated with the current request. getrequestid() returns the request id of the current request object. signature public string getrequestid() 3244apex reference guide resetpasswordresult class return value type: string resetpasswordresult class represents the result of a password reset. namespace system resetpasswordresult methods the following are instance methods for resetpasswordresult. in this section: getpassword() returns the password generated by the system.resetpassword method call. getpassword() returns the password generated by the system.resetpassword method call. signature public string getpassword() return value type: string restcontext class contains the restrequest and restresponse objects. namespace system usage use the system.restcontext class to access the restrequest and restresponse objects in your apex rest methods. 3245apex reference guide restcontext class sample the following example shows how to use restcontext to access the restrequest and restresponse objects in an apex rest method. @restresource(urlmapping='/myrestcontextexample/*') global with sharing class myrestcontextexample { @httpget global static account doget() { restrequest req = restcontext.request; restresponse res = restcontext.response; string accountid = req.requesturi.substring(req.requesturi.lastindexof('/')+1); account result = [select id, name, phone, website from account where id = :accountid]; return result; } } restcontext properties the following are properties for restcontext. in this section: request returns the restrequest for your apex rest method. response returns the restresponse for your apex rest method. request returns the restrequest for your apex rest method. signature public restrequest request {get; set;} property value type: system.restrequest response returns the restresponse for your apex rest method. signature public restresponse response {get; set;} 3246apex reference guide restrequest class property value type: system.restresponse restrequest class use the system.restrequest class to access and pass request data in a restful apex method. namespace system usage an apex restful web service method is defined using one of the rest annotations. for more information about apex restful web service, see exposing apex classes as rest web services. example: an apex class with rest annotated methods the following example shows you how to implement the apex rest api in apex. this class exposes three methods that each handle a different |
http request: get, delete, and post. you can call these annotated methods from a client by issuing http requests. @restresource(urlmapping='/account/*') global with sharing class myrestresource { @httpdelete global static void dodelete() { restrequest req = restcontext.request; restresponse res = restcontext.response; string accountid = req.requesturi.substring(req.requesturi.lastindexof('/')+1); account account = [select id from account where id = :accountid]; delete account; } @httpget global static account doget() { restrequest req = restcontext.request; restresponse res = restcontext.response; string accountid = req.requesturi.substring(req.requesturi.lastindexof('/')+1); account result = [select id, name, phone, website from account where id = :accountid]; return result; } @httppost global static string dopost(string name, string phone, string website) { account account = new account(); account.name = name; account.phone = phone; account.website = website; insert account; 3247apex reference guide restrequest class return account.id; } } in this section: restrequest constructors restrequest properties restrequest methods restrequest constructors the following are constructors for restrequest. in this section: restrequest() creates a new instance of the system.restrequest class. restrequest() creates a new instance of the system.restrequest class. signature public restrequest() restrequest properties the following are properties for restrequest. note: while the restrequest list and map properties are read-only, their contents are read-write. you can modify them by calling the collection methods directly or you can use of the associated restrequest methods shown in the previous table. in this section: headers returns the headers that are received by the request. httpmethod returns one of the supported http request methods. params returns the parameters that are received by the request. remoteaddress returns the ip address of the client making the request. requestbody returns or sets the body of the request. 3248apex reference guide restrequest class requesturi returns or sets everything after the host in the http request string. resourcepath returns the rest resource path for the request. headers returns the headers that are received by the request. signature public map<string, string> headers {get; set;} property value type: map<string, string> httpmethod returns one of the supported http request methods. signature public string httpmethod {get; set;} property value type: string possible values returned: • delete • get • head • patch • post • put params returns the parameters that are received by the request. signature public map <string, string> params {get; set;} property value type: map<string, string> 3249apex reference guide restrequest class remoteaddress returns the ip address of the client making the request. signature public string remoteaddress {get; set;} property value type: string requestbody returns or sets the body of the request. signature public blob requestbody {get; set;} property value type: blob usage if the apex method has no parameters, then apex rest copies the http request body into the restrequest.requestbody property. if there are parameters, then apex rest attempts to deserialize the data into those parameters and the data won't be deserialized into the restrequest.requestbody property. requesturi returns or sets everything after the host in the http request string. signature public string requesturi {get; set;} property value type: string example for example, if the request string is https://instance.salesforce.com/services/apexrest/account/ then the requesturi is /account/. resourcepath returns the rest resource path for the request. 3250apex reference guide restrequest class signature public string resourcepath {get; set;} property value type: string example for example, if the apex rest class defines a urlmapping of /myresource/*, the resourcepath property returns /services/apexrest/myresource/*. restrequest methods the following are methods for restrequest. all are instance methods. note: at runtime, |
you typically don't need to add a header or parameter to the restrequest object because they are automatically deserialized into the corresponding properties. the following methods are intended for unit testing apex rest classes. you can use them to add header or parameter values to the restrequest object without having to recreate the rest method call. in this section: addheader(name, value) adds a header to the request header map in an apex test. addparameter(name, value) adds a parameter to the request params map in an apex test. addheader(name, value) adds a header to the request header map in an apex test. signature public void addheader(string name, string value) parameters name type: string value type: string return value type: void 3251apex reference guide restresponse class usage this method is intended for unit testing of apex rest classes. the following headers aren't allowed: • cookie • set-cookie • set-cookie2 • content-length • authorization if any of these headers are used, an apex exception is thrown. addparameter(name, value) adds a parameter to the request params map in an apex test. signature public void addparameter(string name, string value) parameters name type: string value type: string return value type: void usage this method is intended for unit testing of apex rest classes. restresponse class represents an object used to pass data from an apex restful web service method to an http response. namespace system usage use the system.restresponse class to pass response data from an apex restful web service method that is defined using one of the rest annotations. 3252apex reference guide restresponse class in this section: restresponse constructors restresponse properties restresponse methods restresponse constructors the following are constructors for restresponse. in this section: restresponse() creates a new instance of the system.restresponse class. restresponse() creates a new instance of the system.restresponse class. signature public restresponse() restresponse properties the following are properties for restresponse. note: while the restresponse list and map properties are read-only, their contents are read-write. you can modify them by calling the collection methods directly or you can use of the associated restresponse methods shown in the previous table. in this section: responsebody returns or sets the body of the response. headers returns the headers to be sent to the response. statuscode returns or sets the response status code. responsebody returns or sets the body of the response. signature public blob responsebody {get; set;} 3253apex reference guide restresponse class property value type: blob usage the response is either the serialized form of the method return value or it's the value of the responsebody property based on the following rules: • if the method returns void, then apex rest returns the response in the responsebody property. • if the method returns a value, then apex rest serializes the return value as the response. if the return value contains fields with null value, those fields are not serialized in the response. headers returns the headers to be sent to the response. signature public map<string, string> headers {get; set;} property value type: map<string, string> statuscode returns or sets the response status code. signature public integer statuscode {get; set;} property value type: integer status codes the following are valid response status codes. the status code is returned by the restresponse.statuscode property. note: if you set the restresponse.statuscode property to a value that's not listed in the table, then an http status of 500 is returned with the error message “invalid status code for http response: nnn” where nnn is the invalid status code value. status code description 200 ok 201 created 202 accepted 204 no_content 3254apex reference guide restresponse class status code description 206 partial_content 300 multiple_choices 301 moved_permanently 302 found 304 not_modified 400 bad_request 401 unauthorized 403 forbidden 404 not_found 405 method_not_allowed 406 not_acceptable 409 conflict 410 gone 412 precondition_failed 413 request_ |
entity_too_large 414 request_uri_too_large 415 unsupported_media_type 417 expectation_failed 500 internal_server_error 503 server_unavailable restresponse methods the following are instance methods for restresponse. note: at runtime, you typically don't need to add a header to the restresponse object because it's automatically deserialized into the corresponding properties. the following methods are intended for unit testing apex rest classes. you can use them to add header or parameter values to the restrequest object without having to recreate the rest method call. in this section: addheader(name, value) adds a header to the response header map. 3255apex reference guide sandboxpostcopy interface addheader(name, value) adds a header to the response header map. signature public void addheader(string name, string value) parameters name type: string value type: string return value type: void usage the following headers aren't allowed: • cookie • set-cookie • set-cookie2 • content-length • authorization • header names that aren't rfc 7230 compliant if any of these headers are used, an apex exception is thrown. sandboxpostcopy interface to make your sandbox environment business ready, automate data manipulation or business logic tasks. extend this interface and add methods to perform post-copy tasks, then specify the class during sandbox creation. namespace system usage create an apex class that implements this interface. specify your class during sandbox creation. after your sandbox is created, the runapexclass(context) method in your class runs using the automated process user’s permissions. important: the sandboxpostcopy apex class is executed at the end of the sandbox copy using a special automated process user that isn’t visible within the org. this user doesn’t have access to all object and features; therefore, the apex script cannot access all objects and features. if the script fails, run the script after sandbox activation as a user with appropriate permissions. 3256apex reference guide sandboxpostcopy interface in this section: sandboxpostcopy methods sandboxpostcopy example implementation these examples show a simple implementation of the sandboxpostcopy interface and a test for that implementation. to test your sandboxpostcopy implementation, use the system.test.testsandboxpostcopyscript() method. see also: tooling api: sandboxinfo tooling api: sandboxinfo sandboxpostcopy methods the following method is for sandboxpostcopy. in this section: runapexclass(context) executes actions in a new sandbox to prepare it for use. for example, add logic to this method to create users, run sanitizing code on records, and perform other setup tasks. runapexclass(context) executes actions in a new sandbox to prepare it for use. for example, add logic to this method to create users, run sanitizing code on records, and perform other setup tasks. signature public void runapexclass(system.sandboxcontext context) parameters context type: system.sandboxcontext the org id, sandbox id, and sandbox name for your sandbox. to work with these values, reference context.organizationid(), context.sandboxid(), and context.sandboxname() in your code. return value type: void sandboxpostcopy example implementation these examples show a simple implementation of the sandboxpostcopy interface and a test for that implementation. to test your sandboxpostcopy implementation, use the system.test.testsandboxpostcopyscript() method. important: the sandboxpostcopy apex class is executed at the end of the sandbox copy using a special automated process user that isn’t visible within the org. this user doesn’t have access to all object and features; therefore, the apex script can’t access all objects and features. if the script fails, run the script after sandbox activation as a user with appropriate permissions. 3257apex reference guide sandboxpostcopy interface this example implements the system.sandboxpostcopy interface. global class preparemysandbox implements sandboxpostcopy { global preparemysandbox() { //implementations of sandboxpostcopy must have a no-arg constructor. //this constructor is used during the sandbox copy process. //you can also implement constructors with arguments, but be aware that //they won’t be used by the sandbox copy process (unless |
as part of the //no-arg constructor). this(some_args); } global preparemysandbox(string some_args) { //logic for constructor. } global void runapexclass(sandboxcontext context) { system.debug('org id: ' + context.organizationid()); system.debug('sandbox id: ' + context.sandboxid()); system.debug('sandbox name: ' + context.sandboxname()); // insert logic here to prepare the sandbox for use. } } the following example tests the implementation using the system.test.testsandboxpostcopyscript() method. this method takes four parameters: a reference to a class that implements the sandboxpostcopy interface, and the three fields on the context object that you pass to the runapexclass(context) method. an overload on the method takes an optional boolean parameter to indicate if the test should be performed as the automated process user. @istest class preparemysandboxtest { @istest static void testmysandboxprep() { // insert logic here to create records of the objects that the class you’re testing // manipulates. test.starttest(); //execute test script with runasautoprocuser set to true test.testsandboxpostcopyscript( new preparemysandbox(), userinfo.getorganizationid(), userinfo.getorganizationid(), userinfo.getorganizationname(), true); test.stoptest(); // insert assert statements here to check that the records you created above have // the values you expect. } } 3258apex reference guide schedulable interface for more information on testing, see testing apex. schedulable interface the class that implements this interface can be scheduled to run at different intervals. namespace system see also: apex developer guide: scheduler schedulable methods the following are methods for schedulable. in this section: execute(context) executes the scheduled apex job. execute(context) executes the scheduled apex job. signature public void execute(schedulablecontext context) parameters context type: system.schedulablecontext contains the job id. return value type: void schedulablecontext interface represents the parameter type of a method in a class that implements the schedulable interface and contains the scheduled job id. this interface is implemented internally by apex. 3259apex reference guide schema class namespace system see also: schedulable interface schedulablecontext methods the following are methods for schedulablecontext. in this section: gettriggerid() returns the id of the crontrigger scheduled job. gettriggerid() returns the id of the crontrigger scheduled job. signature public id gettriggerid() return value type: id schema class contains methods for obtaining schema describe information. namespace system schema methods the following are methods for schema. all methods are static. in this section: getglobaldescribe() returns a map of all sobject names (keys) to sobject tokens (values) for the standard and custom objects defined in your organization. describedatacategorygroups(sobjectnames) returns a list of the category groups associated with the specified objects. describesobjects(sobjecttypes) describes metadata (field list and object properties) for the specified sobject or array of sobjects. 3260apex reference guide schema class describesobjects(sobjecttypes, sobjectdescribeoptions) describes metadata such as field list and object properties for the specified list of sobjects. the default describe option for this method is sobjectdescribeoptions.deferred, which indicates lazy initialization of describe attributes on first use. describetabs() returns information about the standard and custom apps available to the running user. describedatacategorygroupstructures(pairs,topcategoriesonly) returns available category groups along with their data category structure for objects specified in the request. getglobaldescribe() returns a map of all sobject names (keys) to sobject tokens (values) for the standard and custom objects defined in your organization. signature public static map<string, schema.sobjecttype> getglobaldescribe() return value type: map<string, schema.sobjecttype> usage for more information on accessing sobjects, see accessing all sobjects. example map<string |
, schema.sobjecttype> gd = schema.getglobaldescribe(); describedatacategorygroups(sobjectnames) returns a list of the category groups associated with the specified objects. signature public static list<schema.describedatacategorygroupresult> describedatacategorygroups(list<string> sobjectnames) parameters sobjectnames type: list<string> return value type: list<schema.describedatacategorygroupresult> 3261apex reference guide schema class usage you can specify one of the following sobject names: • knowledgearticleversion—to retrieve category groups associated with article types. • question—to retrieve category groups associated with questions. for more information and code examples using describedatacategorygroups, see accessing all data categories associated with an sobject. for additional information about articles and questions, see “work with articles and translations” in the salesforce online help. describesobjects(sobjecttypes) describes metadata (field list and object properties) for the specified sobject or array of sobjects. signature public static list<schema.describesobjectresult> describesobjects(list<string> sobjecttypes) parameters sobjecttypes type: list<string> the sobjecttypes argument is a list of sobject type names you want to describe. return value type: list<schema.describesobjectresult> usage this method is similar to the getdescribe method on the schema.sobjecttype token. unlike the getdescribe method, this method allows you to specify the sobject type dynamically and describe more than one sobject at a time. you can first call getglobaldescribe to retrieve a list of all objects for your organization, then iterate through the list and use describesobjects to obtain metadata about individual objects. example schema.describesobjectresult[] descresult = schema.describesobjects( new string[]{'account','contact'}); describesobjects(sobjecttypes, sobjectdescribeoptions) describes metadata such as field list and object properties for the specified list of sobjects. the default describe option for this method is sobjectdescribeoptions.deferred, which indicates lazy initialization of describe attributes on first use. 3262apex reference guide schema class signature public static list<schema.describesobjectresult> describesobjects(list<string> sobjecttypes, object sobjectdescribeoptions) parameters sobjecttypes type: list<string> the list of sobject types to describe. sobjectdescribeoptions type: object the effective describe option used for the sobject. return value type: list<schema.describesobjectresult> describetabs() returns information about the standard and custom apps available to the running user. signature public static list<schema.describetabsetresult> describetabs() return value type: list<schema.describetabsetresult> usage an app is a group of tabs that works as a unit to provide application functionality. for example, two of the standard salesforce apps are “sales” and “service.” the describetabs method returns the minimum required metadata that can be used to render apps in another user interface. typically, this call is used by partner applications to render salesforce data in another user interface, such as in a mobile or connected app. in the salesforce user interface, users have access to standard apps (and can also have access to custom apps) as listed in the salesforce app menu at the top of the page. selecting an app name in the menu allows the user to switch between the listed apps at any time. note: the “all tabs” tab isn’t included in the list of described tabs. example this example shows how to call the describetabs method. schema.describetabsetresult[] tabsetdesc = schema.describetabs(); 3263apex reference guide schema class this longer example shows how to obtain describe metadata information for the sales app. for each tab, the example gets describe information, such as the icon url, whether the tab is custom or not, and colors. the describe information is written to the debug output. // get tab set describes for each app list<schema.describetabsetresult> tabsetdesc = schema.describetabs(); // iterate through each tab set describe for each app |
and display the info for(describetabsetresult tsr : tabsetdesc) { string applabel = tsr.getlabel(); system.debug('label: ' + applabel); system.debug('logo url: ' + tsr.getlogourl()); system.debug('isselected: ' + tsr.isselected()); string ns = tsr.getnamespace(); if (ns == '') { system.debug('the ' + applabel + ' app has no namespace defined.'); } else { system.debug('namespace: ' + ns); } // display tab info for the sales app if (applabel == 'sales') { list<schema.describetabresult> tabdesc = tsr.gettabs(); system.debug('-- tab information for the sales app --'); for(schema.describetabresult tr : tabdesc) { system.debug('getlabel: ' + tr.getlabel()); system.debug('getcolors: ' + tr.getcolors()); system.debug('geticonurl: ' + tr.geticonurl()); system.debug('geticons: ' + tr.geticons()); system.debug('getminiiconurl: ' + tr.getminiiconurl()); system.debug('getsobjectname: ' + tr.getsobjectname()); system.debug('geturl: ' + tr.geturl()); system.debug('iscustom: ' + tr.iscustom()); } } } // example debug statement output // debug|label: sales // debug|logo url: https://mydomainname.my.salesforce.com/img/seasonlogos/2014_winter_aloha.png // debug|isselected: true // debug|the sales app has no namespace defined.// debug|-- tab information for the sales app -- // (this is an example debug output for the accounts tab.) // debug|getlabel: accounts // debug|getcolors: (schema.describecolorresult[getcolor=236fbd;getcontext=primary;gettheme=theme4;], // schema.describecolorresult[getcolor=236fbd;getcontext=primary;gettheme=theme3;], // schema.describecolorresult[getcolor=236fbd;getcontext=primary;gettheme=theme2;]) // debug|geticonurl: https://mydomainname.my.salesforce.com/img/icon/accounts32.png // debug|geticons: (schema.describeiconresult[getcontenttype=image/png;getheight=32;gettheme=theme3; 3264apex reference guide search class // geturl=https://mydomainname.my.salesforce.com/img/icon/accounts32.png;getwidth=32;], // schema.describeiconresult[getcontenttype=image/png;getheight=16;gettheme=theme3; // geturl=https://mydomainname.my.salesforce.com/img/icon/accounts16.png;getwidth=16;]) // debug|getminiiconurl: https://mydomainname.my.salesforce.com/img/icon/accounts16.png // debug|getsobjectname: account // debug|geturl: https://mydomainname.my.salesforce.com/001/o // debug|iscustom: false describedatacategorygroupstructures(pairs,topcategoriesonly) returns available category groups along with their data category structure for objects specified in the request. signature public static list<schema.describedatacategorygroupstructureresult> describedatacategory groupstructures(list<schema.datacategorygroupsobjecttypepair> pairs,boolean topcategoriesonly) parameters pairs type: list<schema.datacategorygroupsobjecttypepair> the pairs argument is one or more category groups and objects to query schema.datacategorygroupsobjecttypepairs. visible data categories are retrieved for the specified object. for more information on data category group visibility, see “data category visibility” in salesforce help. topcategoriesonly type: boolean use true to return only the top visible category and false to return all the visible categories, depending on the user's data category group visibility settings. for more information on data category group visibility, see data category visibility |
in salesforce help. return value type: list<schema.describedatacategorygroupstructureresult> search class use the methods of the search class to perform dynamic sosl queries. namespace system search methods the following are static methods for search. 3265apex reference guide search class in this section: find(searchquery) performs a dynamic sosl query that can include the sosl with snippet clause. snippets provide more context for users in salesforce knowledge article search results. find(searchquery, accesslevel) performs a dynamic sosl query that can include the sosl with snippet clause. snippets provide more context for users in salesforce knowledge article search results. query(query) performs a dynamic sosl query. query(query, accesslevel) performs a dynamic sosl query. suggest(searchquery, sobjecttype, suggestions) returns a list of records or salesforce knowledge articles whose names or titles match the user’s search query string. use this method to provide users with shortcuts to navigate to relevant records or articles before they perform a search. suggest(searchquery, sobjecttype, suggestions, accesslevel) returns a list of records or salesforce knowledge articles whose names or titles match the user’s search query string. use this method to provide users with shortcuts to navigate to relevant records or articles before they perform a search. find(searchquery) performs a dynamic sosl query that can include the sosl with snippet clause. snippets provide more context for users in salesforce knowledge article search results. signature public static search.searchresults find(string searchquery) parameters searchquery type: string a sosl query string. return value type: search.searchresults usage use this method wherever a static sosl query can be used, such as in regular assignment statements and for loops. see use dynamic sosl to return snippets. see also: get(sobjecttype) apex developer guide: dynamic sosl 3266apex reference guide search class find(searchquery, accesslevel) performs a dynamic sosl query that can include the sosl with snippet clause. snippets provide more context for users in salesforce knowledge article search results. signature public static search.searchresults find(string searchquery, system.accesslevel accesslevel) parameters searchquery type: string a sosl query string. accesslevel type: system.accesslevel (optional) the accesslevel parameter specifies whether the method runs in system mode (accesslevel.system_mode) or user mode (accesslevel.user_mode). in system mode, the object and field-level permissions of the current user are ignored, and the record sharing rules are controlled by the class sharing keywords. in user mode, the object permissions, field-level security, and sharing rules of the current user are enforced. system mode is the default. return value type: search.searchresults usage use this method wherever a static sosl query can be used, such as in regular assignment statements and for loops. see use dynamic sosl to return snippets. query(query) performs a dynamic sosl query. signature public static sobject[sobject[]] query(string query) parameters query type: string a sosl query string. to create a sosl query that includes the with snippet clause, use the search.find(string searchquery) method instead. return value type: sobject[sobject[]] 3267apex reference guide search class usage this method can be used wherever a static sosl query can be used, such as in regular assignment statements and for loops. for more information, see dynamic sosl. query(query, accesslevel) performs a dynamic sosl query. signature public static list<list<sobject>> query(string query, system.accesslevel accesslevel) parameters query type: string a sosl query string. to create a sosl query that includes the with snippet clause, use the search.find(string searchquery) method instead. accesslevel type: system.accesslevel (optional) the accesslevel parameter specifies whether the method runs in system mode (accesslevel.system_mode) or user mode (accesslevel.user_mode). in system mode, the object and field-level permissions of the current user are ignored, and the record sharing rules are controlled by the class sharing keywords. in user mode, the object permissions, field- |
level security, and sharing rules of the current user are enforced. system mode is the default. return value type: sobject[sobject[]] usage this method can be used wherever a static sosl query can be used, such as in regular assignment statements and for loops. for more information, see dynamic sosl. suggest(searchquery, sobjecttype, suggestions) returns a list of records or salesforce knowledge articles whose names or titles match the user’s search query string. use this method to provide users with shortcuts to navigate to relevant records or articles before they perform a search. signature public static search.suggestionresults suggest(string searchquery, string sobjecttype, search.suggestionoption suggestions) parameters searchquery type: string 3268apex reference guide search class a sosl query string. sobjecttype type: string an sobject type. options type: search.suggestionoption this object contains options that change the suggestion results. if the searchquery returns knowledgearticleversion objects, pass an options parameter with a search.suggestionoption object that contains a language knowledgesuggestionfilter and a publish status knowledgesuggestionfilter. for suggestions for all other record types, the only supported option is a limit, which sets the maximum number of suggestions returned. return value type: suggestionresults usage use this method to return: suggestions for salesforce knowledge articles (knowledgearticleversion) salesforce knowledge must be enabled in your organization. the user must have the “view articles” permission enabled. the articles suggested include only the articles the user can access, based on the data categories and article types the user has permissions to view. suggestions for other record types the records suggested include only the records the user can access. this method returns a record if its name field starts with the text in the search string. this method automatically appends an asterisk wildcard (*) at the end of the search string. records that contain the search string within a word aren’t considered a match. records are suggested if the entire search string is found in the record name, in the same order as specified in the search string. for example, the text string national u is treated as national u* and returns “national utility” and “national urban company” but not “national company utility” or “urban national company”. note: if the user’s search query contains quotation marks or wildcards, those symbols are automatically removed from the query string in the uri. see also: apex developer guide: suggest salesforce knowledge articles suggest(searchquery, sobjecttype, suggestions, accesslevel) returns a list of records or salesforce knowledge articles whose names or titles match the user’s search query string. use this method to provide users with shortcuts to navigate to relevant records or articles before they perform a search. signature public static search.suggestionresults suggest(string searchquery, string sobjecttype, search.suggestionoption suggestions, system.accesslevel accesslevel) 3269apex reference guide search class parameters searchquery type: string a sosl query string. sobjecttype type: string an sobject type. suggestions type: search.suggestionoption this object contains options that change the suggestion results. if the searchquery returns knowledgearticleversion objects, pass an options parameter with a search.suggestionoption object that contains a language knowledgesuggestionfilter and a publish status knowledgesuggestionfilter. for suggestions for all other record types, the only supported option is a limit, which sets the maximum number of suggestions returned. accesslevel type: system.accesslevel (optional) the accesslevel parameter specifies whether the method runs in system mode (accesslevel.system_mode) or user mode (accesslevel.user_mode). in system mode, the object and field-level permissions of the current user are ignored, and the record sharing rules are controlled by the class sharing keywords. in user mode, the object permissions, field-level security, and sharing rules of the current user are enforced. system mode is the default. return value type: suggestionresults usage use this method to return: suggestions for salesforce knowledge articles (knowledgearticleversion) salesforce knowledge must be enabled in your organization. the user must have the “view articles” permission enabled. the articles suggested include only the articles the user can access, based on the data categories and article types the user has permissions to view. suggestions for other record types the records suggested include only the records the user can access |
. this method returns a record if its name field starts with the text in the search string. this method automatically appends an asterisk wildcard (*) at the end of the search string. records that contain the search string within a word aren’t considered a match. records are suggested if the entire search string is found in the record name, in the same order as specified in the search string. for example, the text string national u is treated as national u* and returns “national utility” and “national urban company” but not “national company utility” or “urban national company”. note: if the user’s search query contains quotation marks or wildcards, those symbols are automatically removed from the query string in the uri. 3270apex reference guide security class security class contains methods to securely implement apex applications. namespace system usage in the context of the current user’s create, read, update, or upsert access permission, use the security class methods to: • strip fields that aren’t visible from query and subquery results • remove inaccessible fields before a dml operation without causing an exception • sanitize sobjects that have been deserialized from an untrusted source in this section: security methods security methods the following are methods for security. in this section: stripinaccessible(accesschecktype, sourcerecords, enforcerootobjectcrud) creates a list of sobjects from the source records, which are stripped of fields that fail the field-level security checks for the current user. the method also provides an option to enforce an object-level access check. stripinaccessible(accesschecktype, sourcerecords) creates a list of sobjects from the source records, which are stripped of fields that fail the field-level security checks for the current user. stripinaccessible(accesschecktype, sourcerecords, enforcerootobjectcrud) creates a list of sobjects from the source records, which are stripped of fields that fail the field-level security checks for the current user. the method also provides an option to enforce an object-level access check. signature public static system.sobjectaccessdecision stripinaccessible(system.accesstype accesschecktype, list<sobject> sourcerecords, boolean enforcerootobjectcrud) parameters accesschecktype type: system.accesstype 3271apex reference guide security class uses values from the accesstype enum. this parameter determines the type of field-level access check to be performed. to check the current user's field-level access, use the schema.describefieldresult methods —iscreatable(), isaccessible(), or isupdatable(). sourcerecords type: list<sobject> a list of sobjects to be checked for fields that aren’t accessible in the context of the current user’s operation. enforcerootobjectcrud type: boolean indicates whether an object-level access check is performed. if this parameter is set to true and the access check fails, the method throws an exception. the default value of this optional parameter is true. return value type: system.sobjectaccessdecision example in this example, the user doesn’t have permission to create the probability field of an opportunity. list<opportunity> opportunities = new list<opportunity>{ new opportunity(name='opportunity1'), new opportunity(name='opportunity2', probability=95) }; // strip fields that are not creatable sobjectaccessdecision decision = security.stripinaccessible( accesstype.creatable, opportunities); // print stripped records for (sobject strippedopportunity : decision.getrecords()) { system.debug(strippedopportunity); } // print modified indexes system.debug(decision.getmodifiedindexes()); // print removed fields system.debug(decision.getremovedfields()); //lines from output log //|debug|opportunity:{name=opportunity1} //|debug|opportunity:{name=opportunity2} //|debug|{1} //|debug|{opportunity={probability}} stripinaccessible(accesschecktype, sourcerecords) creates a list of sobjects from the source records, which are stripped of fields that fail the field-level security checks for the current user. 3272apex reference guide security class signature public static system.sobjectaccess |
decision stripinaccessible(system.accesstype accesschecktype, list<sobject> sourcerecords) parameters accesschecktype type: system.accesstype uses values from the accesstype enum. this parameter determines the type of field-level access check to be performed. to check the current user's field-level access, use the schema.describefieldresult methods —iscreatable(), isaccessible(), or isupdatable(). sourcerecords type: list<sobject> a list of sobjects to be checked for fields that aren’t accessible in the context of the current user’s operation. return value type: system.sobjectaccessdecision example in this example, the user doesn’t have permission to read the actualcost field of a campaign. list<campaign> campaigns = new list<campaign>{ new campaign(name='campaign1', budgetedcost=1000, actualcost=2000), new campaign(name='campaign2', budgetedcost=4000, actualcost=1500) }; insert campaigns; // strip fields that are not readable sobjectaccessdecision decision = security.stripinaccessible( accesstype.readable, [select name, budgetedcost, actualcost from campaign]); // print stripped records for (sobject strippedcampaign : decision.getrecords()) { system.debug(strippedcampaign); // does not display actualcost } // print modified indexes system.debug(decision.getmodifiedindexes()); // print removed fields system.debug(decision.getremovedfields()); //lines from output log //|debug|campaign:{name=campaign1, budgetedcost=1000, id=701xx00000011nhaaa} //|debug|campaign:{name=campaign2, budgetedcost=4000, id=701xx00000011niaaa} //|debug|{0, 1} //|debug|{campaign={actualcost}} 3273apex reference guide selectoption class selectoption class a selectoption object specifies one of the possible values for a visualforce selectcheckboxes, selectlist, or selectradio component. namespace system selectoption consists of a label that is displayed to the end user, and a value that is returned to the controller if the option is selected. a selectoption can also be displayed in a disabled state, so that a user cannot select it as an option, but can still view it. instantiation in a custom controller or controller extension, you can instantiate a selectoption in one of the following ways: • selectoption option = new selectoption(value, label, isdisabled); where value is the string that is returned to the controller if the option is selected by a user, label is the string that is displayed to the user as the option choice, and isdisabled is a boolean that, if true, specifies that the user cannot select the option, but can still view it. • selectoption option = new selectoption(value, label); where value is the string that is returned to the controller if the option is selected by a user, and label is the string that is displayed to the user as the option choice. because a value for isdisabled is not specified, the user can both view and select the option. example the following example shows how a list of selectoptions objects can be used to provide possible values for a selectcheckboxes component on a visualforce page. in the following custom controller, the getitems method defines and returns the list of possible selectoption objects: public class samplecon { string[] countries = new string[]{}; public pagereference test() { return null; } public list<selectoption> getitems() { list<selectoption> options = new list<selectoption>(); options.add(new selectoption('us','us')); options.add(new selectoption('canada','canada')); options.add(new selectoption('mexico','mexico')); return options; } public string[] getcountries() { return countries; } 3274apex reference guide selectoption class public void setcountries(string[] countries) { this.countries = countries; } } in the following page markup, the <apex:selectoptions> tag uses the getitems method from the controller above to retrieve the list of possible values. because <apex:selectoptions> is a child of the <apex:selectcheckboxes> tag, the options are displayed as checkboxes: <apex:page controller="samplecon"> <apex |
:form> <apex:selectcheckboxes value="{!countries}"> <apex:selectoptions value="{!items}"/> </apex:selectcheckboxes><br/> <apex:commandbutton value="test" action="{!test}" rerender="out" status="status"/> </apex:form> <apex:outputpanel id="out"> <apex:actionstatus id="status" starttext="testing..."> <apex:facet name="stop"> <apex:outputpanel> <p>you have selected:</p> <apex:datalist value="{!countries}" var="c">{!c}</apex:datalist> </apex:outputpanel> </apex:facet> </apex:actionstatus> </apex:outputpanel> </apex:page> in this section: selectoption constructors selectoption methods selectoption constructors the following are constructors for selectoption. in this section: selectoption(value, label) creates a new instance of the selectoption class using the specified value and label. selectoption(value, label, isdisabled) creates a new instance of the selectoption class using the specified value, label, and disabled setting. selectoption(value, label) creates a new instance of the selectoption class using the specified value and label. 3275apex reference guide selectoption class signature public selectoption(string value, string label) parameters value type: string the string that is returned to the visualforce controller if the option is selected by a user. label type: string the string that is displayed to the user as the option choice. selectoption(value, label, isdisabled) creates a new instance of the selectoption class using the specified value, label, and disabled setting. signature public selectoption(string value, string label, boolean isdisabled) parameters value type: string the string that is returned to the visualforce controller if the option is selected by a user. label type: string the string that is displayed to the user as the option choice. isdisabled type: boolean if set to true, the option can’t be selected by the user but can still be viewed. selectoption methods the following are methods for selectoption. all are instance methods. in this section: getdisabled() returns the current value of the selectoption object's isdisabled attribute. getescapeitem() returns the current value of the selectoption object's itemescaped attribute. getlabel() returns the option label that is displayed to the user. 3276apex reference guide selectoption class getvalue() returns the option value that is returned to the controller if a user selects the option. setdisabled(isdisabled) sets the value of the selectoption object's isdisabled attribute. setescapeitem(itemsescaped) sets the value of the selectoption object's itemescaped attribute. setlabel(label) sets the value of the option label that is displayed to the user. setvalue(value) sets the value of the option value that is returned to the controller if a user selects the option. getdisabled() returns the current value of the selectoption object's isdisabled attribute. signature public boolean getdisabled() return value type: boolean usage if isdisabled is set to true, the user can view the option, but cannot select it. if isdisabled is set to false, the user can both view and select the option. getescapeitem() returns the current value of the selectoption object's itemescaped attribute. signature public boolean getescapeitem() return value type: boolean usage if itemescaped is set to true, sensitive html and xml characters are escaped in the html output generated by this component. if itemescaped is set to false, items are rendered as written. getlabel() returns the option label that is displayed to the user. 3277apex reference guide selectoption class signature public string getlabel() return value type: string getvalue() returns the option value that is returned to the controller if a user selects the option. signature public string getvalue() return value type: string setdisabled(isdisabled) sets the value of the selectoption object's isdisabled attribute. signature public void setdisabled(boo |
lean isdisabled) parameters isdisabled type: boolean return value type: void usage if isdisabled is set to true, the user can view the option, but cannot select it. if isdisabled is set to false, the user can both view and select the option. setescapeitem(itemsescaped) sets the value of the selectoption object's itemescaped attribute. signature public void setescapeitem(boolean itemsescaped) 3278apex reference guide set class parameters itemsescaped type: boolean return value type: void usage if itemescaped is set to true, sensitive html and xml characters are escaped in the html output generated by this component. if itemescaped is set to false, items are rendered as written. setlabel(label) sets the value of the option label that is displayed to the user. signature public void setlabel(string label) parameters label type: string return value type: void setvalue(value) sets the value of the option value that is returned to the controller if a user selects the option. signature public void setvalue(string value) parameters value type: string return value type: void set class represents a collection of unique elements with no duplicate values. 3279apex reference guide set class namespace system usage the set methods work on a set, that is, an unordered collection of elements that was initialized using the set keyword. set elements can be of any data type—primitive types, collections, sobjects, user-defined types, and built-in apex types. set methods are all instance methods, that is, they all operate on a particular instance of a set. the following are the instance methods for sets. note: • uniqueness of set elements of user-defined types is determined by the equals and hashcode methods, which you provide in your classes. uniqueness of all other non-primitive types is determined by comparing the objects’ fields. • if the set contains string elements, the elements are case-sensitive. two set elements that differ only by case are considered distinct. for more information on sets, see sets. in this section: set constructors set methods set constructors the following are constructors for set. in this section: set<t>() creates a new instance of the set class. a set can hold elements of any data type t. set<t>(settocopy) creates a new instance of the set class by copying the elements of the specified set. t is the data type of the elements in both sets and can be any data type. set<t>(listtocopy) creates a new instance of the set class by copying the list elements. t is the data type of the elements in the set and list and can be any data type. set<t>() creates a new instance of the set class. a set can hold elements of any data type t. signature public set<t>() 3280apex reference guide set class example // create a set of strings set<string> s1 = new set<string>(); // add two strings to it s1.add('item1'); s1.add('item2'); set<t>(settocopy) creates a new instance of the set class by copying the elements of the specified set. t is the data type of the elements in both sets and can be any data type. signature public set<t>(set<t> settocopy) parameters settocopy type: set<t> the set to initialize this set with. example set<string> s1 = new set<string>(); s1.add('item1'); s1.add('item2'); set<string> s2 = new set<string>(s1); // the set elements in s2 are copied from s1 system.debug(s2); set<t>(listtocopy) creates a new instance of the set class by copying the list elements. t is the data type of the elements in the set and list and can be any data type. signature public set<t>(list<t> listtocopy) parameters listtocopy type: integer the list to copy the elements of into this set. 3281apex reference guide set class example list<integer> ls = new list<integer>(); ls.add(1); ls.add(2 |
); // create a set based on a list set<integer> s1 = new set<integer>(ls); // elements are copied from the list to this set system.debug(s1);// debug|{1, 2} set methods the following are methods for set. all are instance methods. in this section: add(setelement) adds an element to the set if it is not already present. addall(fromlist) adds all of the elements in the specified list to the set if they are not already present. addall(fromset) adds all of the elements in the specified set to the set that calls the method if they are not already present. clear() removes all of the elements from the set. clone() makes a duplicate copy of the set. contains(setelement) returns true if the set contains the specified element. containsall(listtocompare) returns true if the set contains all of the elements in the specified list. the list must be of the same type as the set that calls the method. containsall(settocompare) returns true if the set contains all of the elements in the specified set. the specified set must be of the same type as the original set that calls the method. equals(set2) compares this set with the specified set and returns true if both sets are equal; otherwise, returns false. hashcode() returns the hashcode corresponding to this set and its contents. isempty() returns true if the set has zero elements. remove(setelement) removes the specified element from the set if it is present. removeall(listofelementstoremove) removes the elements in the specified list from the set if they are present. 3282 |
apex reference guide set class removeall(setofelementstoremove) removes the elements in the specified set from the original set if they are present. retainall(listofelementstoretain) retains only the elements in this set that are contained in the specified list. retainall(setofelementstoretain) retains only the elements in the original set that are contained in the specified set. size() returns the number of elements in the set (its cardinality). tostring() returns the string representation of the set. add(setelement) adds an element to the set if it is not already present. signature public boolean add(object setelement) parameters setelement type: object return value type: boolean usage this method returns true if the original set changed as a result of the call. for example: set<string> mystring = new set<string>{'a', 'b', 'c'}; boolean result = mystring.add('d'); system.assertequals(true, result); addall(fromlist) adds all of the elements in the specified list to the set if they are not already present. signature public boolean addall(list<object> fromlist) parameters fromlist type: list 3283apex reference guide set class return value type: boolean returns true if the original set changed as a result of the call. usage this method results in the union of the list and the set. the list must be of the same type as the set that calls the method. addall(fromset) adds all of the elements in the specified set to the set that calls the method if they are not already present. signature public boolean addall(set<object> fromset) parameters fromset type: set<object> return value type: boolean this method returns true if the original set changed as a result of the call. usage this method results in the union of the two sets. the specified set must be of the same type as the original set that calls the method. example set<string> mystring = new set<string>{'a', 'b'}; set<string> sstring = new set<string>{'c'}; boolean result1 = mystring.addall(sstring); system.assertequals(true, result1); clear() removes all of the elements from the set. signature public void clear() return value type: void 3284apex reference guide set class clone() makes a duplicate copy of the set. signature public set<object> clone() return value type: set (of same type) contains(setelement) returns true if the set contains the specified element. signature public boolean contains(object setelement) parameters setelement type: object return value type: boolean example set<string> mystring = new set<string>{'a', 'b'}; boolean result = mystring.contains('z'); system.assertequals(false, result); containsall(listtocompare) returns true if the set contains all of the elements in the specified list. the list must be of the same type as the set that calls the method. signature public boolean containsall(list<object> listtocompare) parameters listtocompare type: list<object> return value type: boolean 3285apex reference guide set class containsall(settocompare) returns true if the set contains all of the elements in the specified set. the specified set must be of the same type as the original set that calls the method. signature public boolean containsall(set<object> settocompare) parameters settocompare type: set<object> return value type: boolean example set<string> mystring = new set<string>{'a', 'b'}; set<string> sstring = new set<string>{'c'}; set<string> rstring = new set<string>{'a', 'b', 'c'}; boolean result1, result2; result1 = mystring.addall(sstring); system.assertequals(true, result1); result2 = mystring.containsall(rstring); system.assertequals(true, result2); equals(set2) compares this set with the specified set and returns true if both sets are |
equal; otherwise, returns false. signature public boolean equals(set<object> set2) parameters set2 type: set<object> the set2 argument is the set to compare this set with. return value type: boolean 3286apex reference guide set class usage two sets are equal if their elements are equal, regardless of their order. the == operator is used to compare the elements of the sets. the == operator is equivalent to calling the equals method, so you can call set1.equals(set2); instead of set1 == set2;. hashcode() returns the hashcode corresponding to this set and its contents. signature public integer hashcode() return value type: integer isempty() returns true if the set has zero elements. signature public boolean isempty() return value type: boolean example set<integer> myset = new set<integer>(); boolean result = myset.isempty(); system.assertequals(true, result); remove(setelement) removes the specified element from the set if it is present. signature public boolean remove(object setelement) parameters setelement type: object 3287apex reference guide set class return value type: boolean returns true if the original set changed as a result of the call. removeall(listofelementstoremove) removes the elements in the specified list from the set if they are present. signature public boolean removeall(list<object> listofelementstoremove) parameters listofelementstoremove type: list<object> return value type: boolean returns true if the original set changed as a result of the call. usage this method results in the relative complement of the two sets. the list must be of the same type as the set that calls the method. example set<integer> myset = new set<integer>{1, 2, 3}; list<integer> mylist = new list<integer>{1, 3}; boolean result = myset.removeall(mylist); system.assertequals(true, result); integer result2 = myset.size(); system.assertequals(1, result2); removeall(setofelementstoremove) removes the elements in the specified set from the original set if they are present. signature public boolean removeall(set<object> setofelementstoremove) parameters setofelementstoremove type: set<object> 3288apex reference guide set class return value type: boolean this method returns true if the original set changed as a result of the call. usage this method results in the relative complement of the two sets. the specified set must be of the same type as the original set that calls the method. retainall(listofelementstoretain) retains only the elements in this set that are contained in the specified list. signature public boolean retainall(list<object> listofelementstoretain) parameters listofelementstoretain type: list<object> return value type: boolean this method returns true if the original set changed as a result of the call. usage this method results in the intersection of the list and the set. the list must be of the same type as the set that calls the method. example set<integer> myset = new set<integer>{1, 2, 3}; list<integer> mylist = new list<integer>{1, 3}; boolean result = myset.retainall(mylist); system.assertequals(true, result); retainall(setofelementstoretain) retains only the elements in the original set that are contained in the specified set. signature public boolean retainall(set setofelementstoretain) 3289apex reference guide set class parameters setofelementstoretain type: set return value type: boolean returns true if the original set changed as a result of the call. usage this method results in the intersection of the two sets. the specified set must be of the same type as the original set that calls the method. size() returns the number of elements in the set (its cardinality). signature public integer size() return value type: integer example set<integer> myset = new set<integer>{1, 2, 3}; list<integer> mylist = new list<integer>{1 |
, 3}; boolean result = myset.retainall(mylist); system.assertequals(true, result); integer result2 = myset.size(); system.assertequals(2, result2); tostring() returns the string representation of the set. signature public string tostring() return value type: string 3290apex reference guide site class usage when used in cyclic references, the output is truncated to prevent infinite recursion. when used with large collections, the output is truncated to avoid exceeding total heap size and maximum cpu time. • up to 10 items per collection are included in the output, followed by an ellipsis (…). • if the same object is included multiple times in a collection, it’s shown in the output only once; subsequent references are shown as (already output). site class use the site class to manage your sites. change, reset, validate, and check the expiration of passwords. create site users, person accounts, and portal users. get the admin email and id. get various urls, the path prefix, the id, the template, and the type of the site. log in to the site. namespace system site methods the following are methods for site. all methods are static. in this section: changepassword(newpassword, verifynewpassword, oldpassword) changes the password of the current user. createexternaluser(user, accountid) creates a salesforce site or experience cloud site user for the given account and associates it with the site. createexternaluser(user, accountid, password) creates a salesforce site or experience cloud site user for the given account and associates it with the site. this method sends an email with the specified password to the user. createexternaluser(user, accountid, password, sendemailconfirmation) creates a salesforce site or experience cloud site user and associates it with the given account. this method sends the user an email with the specified password and a new user confirmation email. createpersonaccountportaluser(user, ownerid, password) creates a person account using the default record type defined on the guest user's profile, then enables it for the site's portal. createpersonaccountportaluser(user, ownerid, recordtypeid, password) creates a person account using the specified recordtypeid, then enables it for the site's portal. createportaluser(user, accountid, password, sendemailconfirmation) creates a portal user for the given account and associates it with the site's portal. forgotpassword(username, emailtemplatename) resets the user's password and sends an email to the user with the user’s new password. you can specify a custom email template or use the default email template. returns a value indicating whether the password reset was successful. 3291apex reference guide site class forgotpassword(username) resets the user's password and sends an email to the user with the user’s new password. returns a value indicating whether the password reset was successful. getadminemail() returns the email address of the site administrator. getadminid() returns the user id of the site administrator. getanalyticstrackingcode() the tracking code associated with your site. services such as google analytics can use this code to track page request data for your site. getcurrentsiteurl() deprecated. this method was replaced by getbaseurl() in api version 30.0. returns the base url of the current site that references and links should use. getbasecustomurl() returns a base url for the current site that doesn’t use a force.com subdomain. the returned url uses the same protocol (http or https) as the current request if at least one non-force.com custom url that supports https exists on the site. the returned value never ends with a / character. if all the custom urls in this site end in force.com or this site has no custom urls, then this returns an empty string. if the current request is not a site request, then this method returns an empty string. this method replaced getcustomwebaddress and includes the custom url's path prefix.. getbaseinsecureurl() deprecated. returns a base url for the current site that uses http instead of https. the current request's domain is used. the returned value includes the path prefix and never ends with a / character. if the current request is not a site request, then this method returns an empty string. getbaserequesturl() returns the base url of the current site for the requested url |
. this isn't influenced by the referring page's url. the returned url uses the same protocol (http or https) as the current request. the returned value includes the path prefix and never ends with a / character. if the current request is not a site request, then this method returns an empty string. getbasesecureurl() returns a base url for the current site that uses https instead of http. the current request's domain is preferred if it supports https. domains that are not force.com subdomains are preferred over force.com subdomains. a force.com subdomain, if associated with the site, is used if no other https domains exist in the current site. if no https custom urls exist in the site, then this method returns an empty string. the returned value includes the path prefix and never ends with a / character. if the current request is not a site request, then this method returns an empty string. getbaseurl() returns the base url of the current site that references and links should use. note that this field may return the referring page's url instead of the current request's url. the returned value includes the path prefix and never ends with a / character. if the current request is not a site request, then this field returns an empty string. this field replaces getcurrentsiteurl. getcustomwebaddress() deprecated. this method was replaced by getbasecustomurl() in api version 30.0. getdomain() returns your salesforce sites based url. geterrordescription() returns the error description for the current page if it’s a designated error page for the site and an error exists; otherwise, returns an empty string. 3292apex reference guide site class geterrormessage() returns an error message for the current page if it’s a designated error page for the site and an error exists; otherwise, returns an empty string. getexperienceid() returns the value of the experience id (expid). this expid value comes from a cookie in the user’s web browser. getmasterlabel() returns the value of the master label field for the current site. if the current request is not a site request, then this field returns null. getname() returns the api name of the current site. getoriginalurl() returns the original url for this page if it’s a designated error page for the site; otherwise, returns null. getpasswordpolicystatement() returns the password requirements for a salesforce site or experience cloud site created with the customer service template. getpathprefix() returns the url path prefix of the current site or an empty string if none. for example, if the requested site url is https://myco.my.salesforce-sites.com/partners, then /partners is the path prefix. if the current request is not a site request, then this method returns an empty string. this method replaced getprefix in api version 30.0. getprefix() deprecated. this method was replaced by getpathprefix() in api version 30.0. getsiteid() returns the id of the current site. if the current request is not a site request, then this field returns null. gettemplate() returns the template name associated with the current site; returns the default template if no template has been designated. getsitetype() returns the api value of the site type field for the current site. this can be visualforce for a salesforce site, siteforce for a site.com site, chatternetwork for an experience cloud site, or chatternetworkpicasso for an experience cloud site. if the current request is not a site request, then this method returns null. getsitetypelabel() returns the value of the site type field's label for the current site. if the current request is not a site request, then this method returns null. isloginenabled() returns true if the current site is associated with an active login-enabled portal; otherwise returns false. ispasswordexpired() for authenticated users, returns true if the currently logged-in user's password is expired. for non-authenticated users, returns false. isregistrationenabled() returns true if the current site is associated with an active self-registration-enabled customer portal; otherwise returns false. isvalidusername(username) returns true if the given username is valid; otherwise, returns false. login(username, password, starturl) allows users to log in to the current site with the given username and password, then takes them to the starturl. if starturl is not a relative path, it defaults to the site's designated index page. 3293apex reference guide site class password |
lesslogin(userid, methods, starturl) logs in a user to a salesforce site or experience cloud site using an identity verification method, such as email or text, instead of a password. passwordless login is a convenient, mobile-centric way to welcome users into your site. let your users log in with something other than their password, like their email address or phone number. setexperienceid(expidvalue) sets the experience id for the current user. use this method to populate the value of the experience id (expid) cookie in the user’s web browser. setportaluserasauthprovider(user, contactid) sets the specified user information within the site’s portal via an authentication provider. validatepassword(user, password, confirmpassword) indicates whether a given password meets the requirements specified by org-wide or profile-based password policies in the current user’s org. changepassword(newpassword, verifynewpassword, oldpassword) changes the password of the current user. signature public static system.pagereference changepassword(string newpassword, string verifynewpassword, string oldpassword) parameters newpassword type: string verifynewpassword type: string oldpassword type: string optional only if the current user’s password has expired; otherwise, required. return value type: system.pagereference usage calls to this method in api version 30.0 and later can’t commit the transaction automatically. calls to this method before api version 30.0 commit the transaction, making it impossible to roll back to a save point before the call. createexternaluser(user, accountid) creates a salesforce site or experience cloud site user for the given account and associates it with the site. signature public static id createexternaluser(sobject user, string accountid) 3294apex reference guide site class parameters user type: sobject information required to create a user. the email address of the user is used to look for matching contacts associated with the specified accountid. if a matching contact is found and is already used by an external user, self-registration isn’t successful. if a matching contact is found but isn’t used by an external user, it is used for the new external user. if there is no matching contact, a new contact is created for the new external user. accountid type: string the id of the account you want to associate the user with. return value type: id the id of the user that this method creates. usage this method throws site.externalusercreateexception when user creation fails. the nickname field is required for the user sobject when using the createexternaluser method. note: this method is only valid when a site is associated with a customer portal. calls to this method in api version 30.0 and later can’t commit the transaction automatically. calls to this method before api version 30.0 commit the transaction, making it impossible to roll back to a save point before the call. createexternaluser(user, accountid, password) creates a salesforce site or experience cloud site user for the given account and associates it with the site. this method sends an email with the specified password to the user. signature public static id createexternaluser(sobject user, string accountid, string password) parameters user type: sobject information required to create a user. the email address of the user is used to look for matching contacts associated with the specified accountid. if a matching contact is found and is already used by an external user, self-registration isn’t successful. if a matching contact is found but isn’t used by an external user, it is used for the new external user. if there is no matching contact, a new contact is created for the new external user. accountid type: string the id of the account you want to associate the user with. 3295apex reference guide site class password type: string the password of the salesforce site or experience cloud site user. if not specified, or if set to null or an empty string, this method sends a new password email to the portal user. return value type: id the id of the user that this method creates. usage this method throws site.externalusercreateexception when user creation fails. the nickname field is required for the user sobject when using the createexternaluser method. note: this method is only valid when a site is associated with a customer portal. calls to this method in api version 30.0 and later |
can’t commit the transaction automatically. calls to this method before api version 30.0 commit the transaction, making it impossible to roll back to a save point before the call. createexternaluser(user, accountid, password, sendemailconfirmation) creates a salesforce site or experience cloud site user and associates it with the given account. this method sends the user an email with the specified password and a new user confirmation email. signature public static id createexternaluser(sobject user, string accountid, string password, boolean sendemailconfirmation) parameters user type: sobject information required to create a user. the email address of the user is used to look for matching contacts associated with the specified accountid. if a matching contact is found and is already used by an external user, self-registration isn’t successful. if a matching contact is found but isn’t used by an external user, it is used for the new external user. if there is no matching contact, a new contact is created for the new external user. accountid type: string the id of the account you want to associate the user with. password type: string the password of the salesforce site or experience cloud site user. if not specified, or if set to null or an empty string, this method sends a new password email to the portal user. sendemailconfirmation type: boolean 3296apex reference guide site class determines whether a new user email is sent to the portal user. set it to true to send a new user email to the portal user. the default is false, that is, the new user email isn't sent. return value type: id the id of the user that this method creates. usage this method throws site.externalusercreateexception when user creation fails. the nickname field is required for the user sobject when using the createexternaluser method. note: this method is only valid when a site is associated with a customer portal. calls to this method in api version 30.0 and later can’t commit the transaction automatically. calls to this method before api version 30.0 commit the transaction, making it impossible to roll back to a save point before the call. createpersonaccountportaluser(user, ownerid, password) creates a person account using the default record type defined on the guest user's profile, then enables it for the site's portal. signature public static id createpersonaccountportaluser(sobject user, string ownerid, string password) parameters user type: sobject ownerid type: string password type: string return value type: id usage calls to this method in api version 30.0 and later can’t commit the transaction automatically. calls to this method before api version 30.0 commit the transaction, making it impossible to roll back to a save point before the call. note: this method is only valid when a site is associated with a customer portal, and when the user license for the default new user profile is a high-volume portal user. 3297apex reference guide site class createpersonaccountportaluser(user, ownerid, recordtypeid, password) creates a person account using the specified recordtypeid, then enables it for the site's portal. signature public static id createpersonaccountportaluser(sobject user, string ownerid, string recordtypeid, string password) parameters user type: sobject ownerid type: string recordtypeid type: string password type: string return value type: id usage calls to this method in api version 30.0 and later can’t commit the transaction automatically. calls to this method before api version 30.0 commit the transaction, making it impossible to roll back to a save point before the call. note: this method is only valid when a site is associated with a customer portal, and when the user license for the default new user profile is a high-volume portal user. createportaluser(user, accountid, password, sendemailconfirmation) creates a portal user for the given account and associates it with the site's portal. signature public static id createportaluser(sobject user, string accountid, string password, boolean sendemailconfirmation) parameters user type: sobject accountid type: string password type: string 3298apex reference guide site class (optional) the password of the portal user. if not specified, or if set to null or an empty string, this method sends a new |
password email to the portal user. sendemailconfirmation type: boolean (optional) determines whether a new user email is sent to the portal user. set it to true to send a new user email to the portal user. the default is false, that is, the new user email isn't sent. return value type: id usage if you’re using api version 34.0 or later, we recommend using the createexternaluser() methods because they offer better error handling than this method. the nickname field is required for the user sobject when using the createportaluser method. note: this method is only valid when a site is associated with a customer portal. calls to this method in api version 30.0 and later can’t commit the transaction automatically. calls to this method before api version 30.0 commit the transaction, making it impossible to roll back to a save point before the call. forgotpassword(username, emailtemplatename) resets the user's password and sends an email to the user with the user’s new password. you can specify a custom email template or use the default email template. returns a value indicating whether the password reset was successful. signature public static boolean forgotpassword(string username,string emailtemplatename) parameters username type: string emailtemplatename type: string if provided, the method applies the template to the email. otherwise, the method applies the default system template. if an email template that doesn’t exist is provided, the system logs an exception. return value type: boolean note: the return value is always true unless it’s called outside of a visualforce page. 3299apex reference guide site class usage calls to this method in api version 30.0 and later can’t commit the transaction automatically. calls to this method before api version 30.0 commit the transaction, making it impossible to roll back to a save point before the call. note: site.forgotpassword cannot be used with the @future method, which enables asynchronous execution. forgotpassword(username) resets the user's password and sends an email to the user with the user’s new password. returns a value indicating whether the password reset was successful. signature public static boolean forgotpassword(string username) parameters username type: string return value type: boolean note: the return value is always true unless it’s called outside of a visualforce page. usage calls to this method in api version 30.0 and later can’t commit the transaction automatically. calls to this method before api version 30.0 commit the transaction, making it impossible to roll back to a save point before the call. note: site.forgotpassword cannot be used with the @future method, which enables asynchronous execution. getadminemail() returns the email address of the site administrator. signature public static string getadminemail() return value type: string getadminid() returns the user id of the site administrator. 3300apex reference guide site class signature public static id getadminid() return value type: id getanalyticstrackingcode() the tracking code associated with your site. services such as google analytics can use this code to track page request data for your site. signature public static string getanalyticstrackingcode() return value type: string getcurrentsiteurl() deprecated. this method was replaced by getbaseurl() in api version 30.0. returns the base url of the current site that references and links should use. note that this may return the referring page's url instead of the current request's url. the returned value includes the path prefix and always ends with a / character. if the current request is not a site request, then this method returns null. if the current request is not a site request, then this method returns null. this method was replaced by getbaseurl in api version 30.0. signature public static string getcurrentsiteurl() return value type: string usage use getbaseurl() instead. getbasecustomurl() returns a base url for the current site that doesn’t use a force.com subdomain. the returned url uses the same protocol (http or https) as the current request if at least one non-force.com custom url that supports https exists on the site. the returned value never ends with a / character. if all the custom urls in this site end in force.com or this site has no custom urls, then this returns an empty string. if the current request is not a site request, |
then this method returns an empty string. this method replaced getcustomwebaddress and includes the custom url's path prefix.. signature public static string getbasecustomurl() 3301apex reference guide site class return value type: string usage this method replaces getcustomwebaddress() and includes the custom url's path prefix. getbaseinsecureurl() deprecated. returns a base url for the current site that uses http instead of https. the current request's domain is used. the returned value includes the path prefix and never ends with a / character. if the current request is not a site request, then this method returns an empty string. signature public static string getbaseinsecureurl() return value type: string getbaserequesturl() returns the base url of the current site for the requested url. this isn't influenced by the referring page's url. the returned url uses the same protocol (http or https) as the current request. the returned value includes the path prefix and never ends with a / character. if the current request is not a site request, then this method returns an empty string. signature public static string getbaserequesturl() return value type: string getbasesecureurl() returns a base url for the current site that uses https instead of http. the current request's domain is preferred if it supports https. domains that are not force.com subdomains are preferred over force.com subdomains. a force.com subdomain, if associated with the site, is used if no other https domains exist in the current site. if no https custom urls exist in the site, then this method returns an empty string. the returned value includes the path prefix and never ends with a / character. if the current request is not a site request, then this method returns an empty string. signature public static string getbasesecureurl() return value type: string 3302apex reference guide site class getbaseurl() returns the base url of the current site that references and links should use. note that this field may return the referring page's url instead of the current request's url. the returned value includes the path prefix and never ends with a / character. if the current request is not a site request, then this field returns an empty string. this field replaces getcurrentsiteurl. signature public static string getbaseurl() return value type: string usage this method replaces getcurrentsiteurl(). getcustomwebaddress() deprecated. this method was replaced by getbasecustomurl() in api version 30.0. returns the request's custom url if it doesn't end in lightning platform or returns the site's primary custom url. if neither exist, then this returns null. note that the url's path is always the root, even if the request's custom url has a path prefix. if the current request is not a site request, then this method returns null. the returned value always ends with a / character. signature public static string getcustomwebaddress() return value type: string usage use getbasecustomurl() instead. getdomain() returns your salesforce sites based url. signature public static string getdomain() return value type: string 3303apex reference guide site class geterrordescription() returns the error description for the current page if it’s a designated error page for the site and an error exists; otherwise, returns an empty string. signature public static string geterrordescription() return value type: string geterrormessage() returns an error message for the current page if it’s a designated error page for the site and an error exists; otherwise, returns an empty string. signature public static string geterrormessage() return value type: string getexperienceid() returns the value of the experience id (expid). this expid value comes from a cookie in the user’s web browser. signature public static string getexperienceid() return value type: string usage use the getexperienceid and setexperienceid methods to implement dynamic login experiences. you can set the experience id with setexperienceid or by extending the following endpoints with expid_value. • community-url/services/oauth2/authorize/expid_value • community-url/idp/endpoint/httppost/expid_value • community-url/idp/endpoint/httpredirect/expid_value • community-url_login_page/expid={value} • community-url/communitiesselfreg?expid={value} • secur/ |
forgotpassword.jsp?expid={value} the cookie is set when the browser loads the urls with the expid values. 3304apex reference guide site class getmasterlabel() returns the value of the master label field for the current site. if the current request is not a site request, then this field returns null. signature public static string getmasterlabel() return value type: string getname() returns the api name of the current site. signature public static string getname() return value type: string getoriginalurl() returns the original url for this page if it’s a designated error page for the site; otherwise, returns null. signature public static string getoriginalurl() return value type: string getpasswordpolicystatement() returns the password requirements for a salesforce site or experience cloud site created with the customer service template. signature public static string getpasswordpolicystatement() return value type: string 3305apex reference guide site class getpathprefix() returns the url path prefix of the current site or an empty string if none. for example, if the requested site url is https://myco.my.salesforce-sites.com/partners, then /partners is the path prefix. if the current request is not a site request, then this method returns an empty string. this method replaced getprefix in api version 30.0. signature public static string getpathprefix() return value type: string getprefix() deprecated. this method was replaced by getpathprefix() in api version 30.0. returns the url path prefix of the current site. for example, if your site url is mydomainname.my.salesforce-sites.com/partners, /partners is the path prefix. returns null if the prefix isn’t defined. if the current request is not a site request, then this method returns a null. signature public static string getprefix() return value type: string getsiteid() returns the id of the current site. if the current request is not a site request, then this field returns null. signature public static string getsiteid() return value type: id gettemplate() returns the template name associated with the current site; returns the default template if no template has been designated. signature public static system.pagereference gettemplate() 3306apex reference guide site class return value type: system.pagereference getsitetype() returns the api value of the site type field for the current site. this can be visualforce for a salesforce site, siteforce for a site.com site, chatternetwork for an experience cloud site, or chatternetworkpicasso for an experience cloud site. if the current request is not a site request, then this method returns null. signature public static string getsitetype() return value type: string getsitetypelabel() returns the value of the site type field's label for the current site. if the current request is not a site request, then this method returns null. signature public static string getsitetypelabel() return value type: string isloginenabled() returns true if the current site is associated with an active login-enabled portal; otherwise returns false. signature public static boolean isloginenabled() return value type: boolean ispasswordexpired() for authenticated users, returns true if the currently logged-in user's password is expired. for non-authenticated users, returns false. signature public static boolean ispasswordexpired() 3307apex reference guide site class return value type: boolean isregistrationenabled() returns true if the current site is associated with an active self-registration-enabled customer portal; otherwise returns false. signature public static boolean isregistrationenabled() return value type: boolean isvalidusername(username) returns true if the given username is valid; otherwise, returns false. signature public static boolean isvalidusername(string username) parameters username type: string the username to test for validity. return value type: boolean login(username, password, starturl) allows users to log in to the current site with the given username and password, then takes them to the starturl. if starturl is not a relative path, it defaults to the site's designated index page. signature public static system.pagereference login(string username, string password, string starturl) parameters username type: string password type: |
string 3308apex reference guide site class starturl type: string return value type: system.pagereference usage all dml statements before the call to site.login get committed. it’s not possible to roll back to a save point that was created before a call to site.login. note: do not include http:// or https:// in the starturl. passwordlesslogin(userid, methods, starturl) logs in a user to a salesforce site or experience cloud site using an identity verification method, such as email or text, instead of a password. passwordless login is a convenient, mobile-centric way to welcome users into your site. let your users log in with something other than their password, like their email address or phone number. signature public static system.pagereference passwordlesslogin(id userid, list<auth.verificationmethod> methods, string starturl) parameters userid type: id id of the user to log in. methods type: list<auth.verificationmethod> list of identity verification methods available to the user for passwordless login. starturl type: string path to the page that users see after they log in. return value type: system.pagereference usage include this method in the apex controller of a custom login page implementation. 3309apex reference guide site class passwordlesslogin example this simple code example of an apex controller contains the passwordlesslogin method. the pagereference returned by passwordlesslogin redirects the user to the salesforce verify page. when the user enters the correct code, the user is redirected to the site page specified by the start url. global with sharing class mfilogincontroller { //input variables global string input {get; set;} public string starturl {get; set;} public list<auth.verificationmethod> methods; public string error; global mfilogincontroller() { // add verification methods in priority order methods = new list<auth.verificationmethod>(); methods.add(auth.verificationmethod.sms); methods.add(auth.verificationmethod.email); methods.add(auth.verificationmethod.u2f); methods.add(auth.verificationmethod.salesforce_authenticator); methods.add(auth.verificationmethod.totp); } global pagereference login() { list<user> users = null; // empty input if(input == null || input == '') { error = 'enter username'; return null; } users = [select name, id, email from user where username=:input]; if(users == null || users.isempty()) { error = 'can\'t find a user'; return null; } if (starturl == null) starturl = '/'; return site.passwordlesslogin(users[0].id, methods, starturl); } } setexperienceid(expidvalue) sets the experience id for the current user. use this method to populate the value of the experience id (expid) cookie in the user’s web browser. 3310apex reference guide site class signature public static void setexperienceid(string expidvalue) parameters expidvalue type: string a value that indicates the user’s login experience. the value must contain alphanumeric characters only, up to 30 characters. usage use setexperienceid when you’re implementing dynamic login experiences. a login experience refers to a login page plus any secondary pages associated with the login page (such as multi-factor authentication (mfa) or a login flow). you define different login experiences depending on who users are or where they’re logging in from. for example, you can require a different registration process based on the user’s location. in this case, expidvalue includes a state or country code. when the user logs in, the url contains the experience id parameter, {expid}. the {expid} parameter is replaced by the value stored in expidvalue, such as .jp. then the user is redirected to the japanese login experience. example string expid = apexpages.currentpage().getparameters().get('expid'); if (expid != null) { site.setexperienceid(expid); } setportaluserasauthprovider(user, contactid) sets the specified user information within the site’s portal via an authentication provider. signature |
public static void setportaluserasauthprovider(sobject user, string contactid) parameters user type: sobject contactid type: string return value type: void usage • this method is only valid when a site is associated with a customer portal. 3311apex reference guide sobject class • calls to this method in api version 30.0 and later can’t commit the transaction automatically. calls to this method before api version 30.0 commit the transaction, making it impossible to roll back to a save point before the call. • for more information on an authentication provider, see registrationhandler. validatepassword(user, password, confirmpassword) indicates whether a given password meets the requirements specified by org-wide or profile-based password policies in the current user’s org. signature public static void validatepassword(sobject user, string password, string confirmpassword) parameters user type: sobject the user attempting to create a password during self-registration for a salesforce site or experience cloud site. password type: string the password entered by the user. confirmpassword type: string the password reentered by the user to confirm the password. return value type: void usage if validation fails when the method is run in a lightning controller, this method throws an apex exception describing the failed validation. if validation fails when the method is run in a visualforce controller, the method provides visualforce error messages. sobject class contains methods for the sobject data type. namespace system usage sobject methods are all instance methods: they are called by and operate on an sobject instance such as an account or contact. the following are the instance methods for sobjects. 3312apex reference guide sobject class for more information on sobjects, see working with sobjects. sobject methods the following are methods for sobject. all are instance methods. in this section: adderror(errormsg) marks a trigger record with a custom error message and prevents any dml operation from occurring. adderror(errormsg, escape) marks a trigger record with a custom error message, specifies if the error message should be escaped, and prevents any dml operation from occurring. adderror(exceptionerror) marks a trigger record with a custom error message and prevents any dml operation from occurring. adderror(exceptionerror, escape) marks a trigger record with a custom exception error message, specifies whether or not the exception error message should be escaped, and prevents any dml operation from occurring. adderror(errormsg) places the specified error message on a trigger record field in the salesforce user interface and prevents any dml operation from occurring. adderror(errormsg, escape) places the specified error message, which can be escaped or unescaped, on a trigger record field in the salesforce user interface, and prevents any dml operation from occurring. adderror(fieldname, errormsg) dynamically add errors to fields of an sobject associated with the specified field name. adderror(fieldtoken, errormsg) dynamically add errors to an sobject instance associated with the specified field. adderror(fieldname, errormsg, escape) dynamically add errors to fields of an sobject associated with the specified field name. adderror(fieldtoken, errormsg, escape) dynamically add errors to an sobject instance associated with the specified field. clear() clears all field values clone(preserveid, isdeepclone, preservereadonlytimestamps, preserveautonumber) creates a copy of the sobject record. get(fieldname) returns the value for the field specified by fieldname, such as accountnumber. get(field) returns the value for the field specified by the field token schema.sobjectfield, such as, schema.account.accountnumber. 3313apex reference guide sobject class getclonesourceid() returns the id of the entity from which an object was cloned. you can use it for objects cloned through the salesforce user interface. you can also use it for objects created using the system.sobject.clone(preserveid, isdeepclone, preservereadonlytimestamps, preserveautonumber) method, provided that the preserveid parameter wasn’t used or was set to false. the getclonesourceid() method can only be used within the transaction where the entity is cloned, as clone information doesn’t persist |
in subsequent transactions. geterrors() returns a list of database.error objects for an sobject instance. if the sobject has no errors, an empty list is returned. getoptions() returns the database.dmloptions object for the sobject. getpopulatedfieldsasmap() returns a map of populated field names and their corresponding values. the map contains only the fields that have been populated in memory for the sobject instance. getsobject(fieldname) returns the value for the specified field. this method is primarily used with dynamic dml to access values for external ids. getsobject(field) returns the value for the field specified by the field token schema.sobjectfield, such as, schema.myobj.myexternalid. this method is primarily used with dynamic dml to access values for external ids. getsobjects(fieldname) returns the values for the specified field. this method is primarily used with dynamic dml to access values for associated objects, such as child relationships. getsobjects(fieldname) returns the value for the field specified by the field token schema.fieldname, such as, schema.account.contact. this method is primarily used with dynamic dml to access values for associated objects, such as child relationships. getsobjecttype() returns the token for this sobject. this method is primarily used with describe information. getquickactionname() retrieves the name of a quick action associated with this sobject. typically used in triggers. haserrors() returns true if an sobject instance has associated errors. the error message can be associated to the sobject instance by using sobject.adderror(), validation rules, or by other means. isclone() returns true if an entity is cloned from something, even if the entity hasn’t been saved. the method can only be used within the transaction where the entity is cloned, as clone information doesn’t persist in subsequent transactions. isset(fieldname) returns information about the queried sobject field. returns true if the sobject field is populated, either by direct assignment or by inclusion in a soql query. returns false if the sobject field is not set. if an invalid field is specified, an sobjectexception is thrown. isset(field) returns information about the queried sobject field. returns true if the sobject field is populated, either by direct assignment or by inclusion in a soql query. returns false if the sobject field is not set. if an invalid field is specified, an sobjectexception is thrown. 3314apex reference guide sobject class put(fieldname, value) sets the value for the specified field and returns the previous value for the field. put(field, value) sets the value for the field specified by the field token schema.sobjectfield, such as, schema.account.accountnumber and returns the previous value for the field. putsobject(fieldname, value) sets the value for the specified field. this method is primarily used with dynamic dml for setting external ids. the method returns the previous value of the field. putsobject(fieldname, value) sets the value for the field specified by the token schema.sobjecttype. this method is primarily used with dynamic dml for setting external ids. the method returns the previous value of the field. recalculateformulas() deprecated as of api version 57.0. use the recalculateformulas() method in the system.formula class instead. setoptions(dmloptions) sets the dmloptions object for the sobject. adderror(errormsg) marks a trigger record with a custom error message and prevents any dml operation from occurring. signature public void adderror(string errormsg) parameters errormsg type: string the error message to mark the record with. return value type: void usage when used on trigger.new in before insert and before update triggers, and on trigger.old in before delete triggers, the error message is displayed in the application interface. see triggers and trigger exceptions. note: this method escapes any html markup in the specified error message. the escaped characters are: \n, <, >, &, ", \, \u2028, \u2029, and \u00a9. as a result, html markup is not rendered; instead, it is displayed as text in the salesforce user interface. when used in visualforce controllers, the generated message is added to the collection of |
errors for the page. for more information, see validation rules and standard controllers in the visualforce developer's guide. 3315apex reference guide sobject class example trigger.new[0].adderror('bad'); adderror(errormsg, escape) marks a trigger record with a custom error message, specifies if the error message should be escaped, and prevents any dml operation from occurring. signature public void adderror(string errormsg, boolean escape) parameters errormsg type: string the error message to mark the record with. escape type: boolean indicates whether any html markup in the custom error message should be escaped (true) or not (false). this parameter is ignored in both lightning experience and the salesforce mobile app, and the html is always escaped. the escape parameter only applies in salesforce classic. return value type: void usage the escaped characters are: \n, <, >, &, ", \, \u2028, \u2029, and \u00a9. as a result, html markup is not rendered; instead, it is displayed as text in the salesforce user interface. warning: be cautious if you specify false for the escape argument. unescaped strings displayed in the salesforce user interface can represent a vulnerability in the system because these strings might contain harmful code. if you want to include html markup in the error message, call this method with a false escape argument. make sure that you escape any dynamic content, such as input field values. otherwise, specify true for the escape argument or call adderror(string errormsg) instead. example trigger.new[0].adderror('fix & resubmit', false); adderror(exceptionerror) marks a trigger record with a custom error message and prevents any dml operation from occurring. 3316apex reference guide sobject class signature public void adderror(exception exceptionerror) parameters exceptionerror type: system.exception an exception object or a custom exception object that contains the error message to mark the record with. return value type: void usage when used on trigger.new in before insert and before update triggers, and on trigger.old in before delete triggers, the error message is displayed in the application interface. see triggers and trigger exceptions. note: this method escapes any html markup in the specified error message. the escaped characters are: \n, <, >, &, ", \, \u2028, \u2029, and \u00a9. as a result, html markup is not rendered; instead, it is displayed as text in the salesforce user interface. when used in visualforce controllers, the generated message is added to the collection of errors for the page. for more information, see validation rules and standard controllers in the visualforce developer's guide. example public class myexception extends exception {} trigger.new[0].adderror(new myexception('invalid id')); adderror(exceptionerror, escape) marks a trigger record with a custom exception error message, specifies whether or not the exception error message should be escaped, and prevents any dml operation from occurring. signature public void adderror(exception exceptionerror, boolean escape) parameters exceptionerror type: system.exception an exception object or a custom exception object that contains the error message to mark the record with. escape type: boolean 3317apex reference guide sobject class indicates whether any html markup in the custom error message should be escaped (true) or not (false). this parameter is ignored in both lightning experience and the salesforce mobile app, and the html is always escaped. the escape parameter only applies in salesforce classic. return value type: void usage the escaped characters are: \n, <, >, &, ", \, \u2028, \u2029, and \u00a9. as a result, html markup is not rendered; instead, it is displayed as text in the salesforce user interface. warning: be cautious if you specify false for the escape argument. unescaped strings displayed in the salesforce user interface can represent a vulnerability in the system because these strings might contain harmful code. if you want to include html markup in the error message, call this method with a false escape argument. make sure that you escape any dynamic content, such as input field values. otherwise, specify true for the escape argument or call adderror(exception e) instead. example public class myexception extends exception {} trigger.new[0].adderror(new myexception(' |
invalid id & other issues', false)); adderror(errormsg) places the specified error message on a trigger record field in the salesforce user interface and prevents any dml operation from occurring. signature public void adderror(string errormsg) parameters errormsg type: string return value type: void usage note: • when used on trigger.new in before insert and before update triggers, and on trigger.old in before delete triggers, the error appears in the application interface. • when used in visualforce controllers, if there is an inputfield component bound to field, the message is attached to the component. for more information, see validation rules and standard controllers in the visualforce developer's guide. • this method is highly specialized because the field identifier is not actually the invoking object—the sobject record is the invoker. the field is simply used to identify the field that should be used to display the error. 3318apex reference guide sobject class see triggers and trigger exceptions. note: this method escapes any html markup in the specified error message. the escaped characters are: \n, <, >, &, ", \, \u2028, \u2029, and \u00a9. as a result, html markup is not rendered; instead, it is displayed as text in the salesforce user interface. example trigger.new[0].myfield__c.adderror('bad'); adderror(errormsg, escape) places the specified error message, which can be escaped or unescaped, on a trigger record field in the salesforce user interface, and prevents any dml operation from occurring. signature public void adderror(string errormsg, boolean escape) parameters errormsg type: string the error message to mark the record with. escape type: boolean indicates whether any html markup in the custom error message should be escaped (true) or not (false). this parameter is ignored in both lightning experience and the salesforce mobile app, and the html is always escaped. the escape parameter only applies in salesforce classic. return value type: usage the escaped characters are: \n, <, >, &, ", \, \u2028, \u2029, and \u00a9. as a result, html markup is not rendered; instead, it is displayed as text in the salesforce user interface. warning: be cautious if you specify false for the escape argument. unescaped strings displayed in the salesforce user interface can represent a vulnerability in the system because these strings might contain harmful code. if you want to include html markup in the error message, call this method with a false escape argument. make sure that you escape any dynamic content, such as input field values. otherwise, specify true for the escape argument or call field.adderror(string errormsg) instead. example trigger.new[0].myfield__c.adderror('fix & resubmit', false); 3319apex reference guide sobject class adderror(fieldname, errormsg) dynamically add errors to fields of an sobject associated with the specified field name. signature public void adderror(string fieldname, string errormsg) parameters fieldname type: string the field name of the sobject . errormsg type: string the error message to be added. html special characters in the error message string are always escaped. return value type: void usage if the field name is an empty string or null, the error is associated with the sobject and not with a specific field. example // add an error to an sobject field using the adderror() method. account acct = new account(name = 'testaccount'); acct.adderror('name', 'error in name field'); // use the haserrors() method to verify that the error is added, and then the geterrors() method to validate the error. system.assert(acct.haserrors()); list<database.error> errors = acct.geterrors(); system.assertequals(1, errors.size()); adderror(fieldtoken, errormsg) dynamically add errors to an sobject instance associated with the specified field. signature public void adderror(schema.sobjectfield fieldtoken, string errormsg parameters fieldtoken type: schema.sobjectfield the field of the sobject instance. 3320apex reference guide sobject class errormsg type: string the error message to be added. html special characters in |
the error message string are always escaped. return value type: void usage use this method to add errors to the specified field token of a standard or custom object. if fieldtokenis null, the error is associated with the sobject and not with a specific field. example // add an error to a field of an sobject instance using the adderror() method. account acct = new account(name = 'testaccount'); schema.describefieldresult namedesc = account.name.getdescribe(); schema.sobjectfield namefield = namedesc.getsobjectfield(); acct.adderror(namefield, 'error is name field'); // use the haserrors() method to verify that the error is added, and then the geterrors() method to validate the error. system.assert(acct.haserrors()); list<database.error> errors = acct.geterrors(); system.assertequals(1, errors.size()); adderror(fieldname, errormsg, escape) dynamically add errors to fields of an sobject associated with the specified field name. signature public void adderror(string fieldname, string errormsg, boolean escape) parameters fieldname type: string the field name of the sobject . errormsg type: string the error message to be added. escape type: boolean indicates whether any html markup in the custom error message should be escaped (true) or not (false). this parameter is ignored in both lightning experience and the salesforce mobile app, and the html is always escaped. the escape parameter only applies in salesforce classic. 3321apex reference guide sobject class return value type: void usage if the field name is an empty string or null, the error is associated with the sobject and not with a specific field. the escaped characters are: \n, <, >, &, ", \, \u2028, \u2029, and \u00a9. as a result, html markup is not rendered; instead, it is displayed as text in the salesforce user interface. warning: • the escape parameter cannot be disabled in lightning experience and in the salesforce mobile app, and will be ignored. • be cautious if you specify false for the escape argument. unescaped strings displayed in the salesforce user interface can represent a vulnerability in the system because these strings might contain harmful code. if you want to include html markup in the error message, call this method with a false escape argument. make sure that you escape any dynamic content, such as input field values. otherwise, specify true for the escape argument or call adderror(string fieldname, string errormsg) instead. example // add an error to an sobject field using the adderror() method. account acct = new account(name = 'testaccount'); acct.adderror('name', 'error in name field', false); // use the haserrors() method to verify that the error is added, and then the geterrors() method to validate the error. system.assert(acct.haserrors()); list<database.error> errors = acct.geterrors(); system.assertequals(1, errors.size()); adderror(fieldtoken, errormsg, escape) dynamically add errors to an sobject instance associated with the specified field. signature public void adderror(schema.sobjectfield fieldtoken, string errormsg, boolean escape) parameters fieldtoken type: schema.sobjectfield the field of the sobject instance. errormsg type: string the error message to be added. escape type: boolean 3322apex reference guide sobject class indicates whether any html markup in the custom error message should be escaped (true) or not (false). this parameter is ignored in both lightning experience and the salesforce mobile app, and the html is always escaped. the escape parameter only applies in salesforce classic. return value type: void usage use this method to add errors to the specified field token of a standard or custom object. if fieldtokenis null, the error is associated with the sobject and not with a specific field. the escaped characters are: \n, <, >, &, ", \, \u2028, \u2029, and \u00a9. as a result, html markup is not rendered; instead, it is displayed as text in the salesforce user interface. warning: • the escape parameter cannot be disabled in lightning experience and in the |
salesforce mobile app, and will be ignored. • be cautious if you specify false for the escape argument. unescaped strings displayed in the salesforce user interface can represent a vulnerability in the system because these strings might contain harmful code. if you want to include html markup in the error message, call this method with a false escape argument. make sure that you escape any dynamic content, such as input field values. otherwise, specify true for the escape argument or call adderror(schema.sobjectfield fieldtoken, string errormsg) instead. example // add an error to a field of an sobject instance using the adderror() method. account acct = new account(name = 'testaccount'); schema.describefieldresult namedesc = account.name.getdescribe(); schema.sobjectfield namefield = namedesc.getsobjectfield(); acct.adderror(namefield, 'error is name field', false); // use the haserrors() method to verify that the error is added, and then the geterrors() method to validate the error. system.assert(acct.haserrors()); list<database.error> errors = acct.geterrors(); system.assertequals(1, errors.size()); clear() clears all field values signature public void clear() return value type: void 3323apex reference guide sobject class example account acc = new account(name = 'acme'); acc.clear(); account expected = new account(); system.assertequals(expected, acc); clone(preserveid, isdeepclone, preservereadonlytimestamps, preserveautonumber) creates a copy of the sobject record. signature public sobject clone(boolean preserveid, boolean isdeepclone, boolean preservereadonlytimestamps, boolean preserveautonumber) parameters preserveid type: boolean (optional) determines whether the id of the original object is preserved or cleared in the duplicate. if set to true, the id is copied to the duplicate. the default is false, that is, the id is cleared. isdeepclone type: boolean (optional) determines whether the method creates a full copy of the sobject field or just a reference: • if set to true, the method creates a full copy of the sobject. all fields on the sobject are duplicated in memory, including relationship fields. consequently, if you change a field on the cloned sobject, the original sobject isn’t affected. • if set to false, the method performs a shallow copy of the sobject fields. all copied relationship fields reference the original sobjects. consequently, if you change a relationship field on the cloned sobject, the corresponding field on the original sobject is also affected, and vice versa. the default is false. preservereadonlytimestamps type: boolean (optional) determines whether the read-only timestamp fields are preserved or cleared in the duplicate. if set to true, the read-only fields createdbyid, createddate, lastmodifiedbyid, and lastmodifieddate are copied to the duplicate. the default is false, that is, the values are cleared. note: audit field values won’t be persisted to the database via dml on the cloned sobject instance. preserveautonumber type: boolean (optional) determines whether auto number fields of the original object are preserved or cleared in the duplicate. if set to true, auto number fields are copied to the cloned object. the default is false, that is, auto number fields are cleared. return value type: sobject (of the same type) 3324apex reference guide sobject class usage note: for apex saved using salesforce api version 22.0 or earlier, the default value for the preserveid argument is true, that is, the id is preserved. example account acc = new account(name = 'acme', description = 'acme account'); account clonedacc = acc.clone(false, false, false, false); system.assertequals(acc, clonedacc); get(fieldname) returns the value for the field specified by fieldname, such as accountnumber. signature public object get(string fieldname) parameters fieldname type: string return value type: object usage for more information, see dynamic soql. example account acc = new account(name = 'acme', description = 'acme account'); string description = |
(string)acc.get('description'); system.assertequals('acme account', description); versioned behavior changes in api version 34.0 and later, you must include the namespace name to retrieve a field from a field map using this method. for example, to get the account__c field in the mynamespace namespace from a fields field map, use: fields.get(‘mynamespace__account__c’). get(field) returns the value for the field specified by the field token schema.sobjectfield, such as, schema.account.accountnumber. 3325apex reference guide sobject class signature public object get(schema.sobjectfield field) parameters field type: schema.sobjectfield return value type: object usage for more information, see dynamic soql. note: field tokens aren't available for person accounts. if you access schema.account.fieldname, you get an exception error. instead, specify the field name as a string. example account acc = new account(name = 'acme', description = 'acme account'); string description = (string)acc.get(schema.account.description); system.assertequals('acme account', description); getclonesourceid() returns the id of the entity from which an object was cloned. you can use it for objects cloned through the salesforce user interface. you can also use it for objects created using the system.sobject.clone(preserveid, isdeepclone, preservereadonlytimestamps, preserveautonumber) method, provided that the preserveid parameter wasn’t used or was set to false. the getclonesourceid() method can only be used within the transaction where the entity is cloned, as clone information doesn’t persist in subsequent transactions. signature public id getclonesourceid() return value type: id usage if a is cloned to b, b is cloned to c, and c is cloned to d, then b, c, and d all point back to a as their clone source. example account acc0 = new account(name = 'acme'); insert acc0; account acc1 = acc0.clone(); 3326apex reference guide sobject class account acc2 = acc1.clone(); account acc3 = acc2.clone(); account acc4 = acc3.clone(); system.assert(acc0.id != null); system.assertequals(acc0.id, acc1.getclonesourceid()); system.assertequals(acc0.id, acc2.getclonesourceid()); system.assertequals(acc0.id, acc3.getclonesourceid()); system.assertequals(acc0.id, acc4.getclonesourceid()); system.assertequals(null, acc0.getclonesourceid()); geterrors() returns a list of database.error objects for an sobject instance. if the sobject has no errors, an empty list is returned. signature public list<database.error> geterrors() return value type: list<database.error> getoptions() returns the database.dmloptions object for the sobject. signature public database.dmloptions getoptions() return value type: database.dmloptions example database.dmloptions dmo = new database.dmloptions(); dmo.assignmentruleheader.usedefaultrule = true; account acc = new account(name = 'acme'); acc.setoptions(dmo); database.dmloptions accdmo = acc.getoptions(); getpopulatedfieldsasmap() returns a map of populated field names and their corresponding values. the map contains only the fields that have been populated in memory for the sobject instance. signature public map<string,object> getpopulatedfieldsasmap() 3327apex reference guide sobject class return value type: map<string,object> a map of field names and their corresponding values. usage the returned map contains only the fields that have been populated in memory for the sobject instance, which makes it easy to iterate over those fields. a field is populated in memory in the following cases. • the field has been queried by a soql statement. • the field has been explicitly set before the call to the getpopulatedfieldsasmap() method. fields on related objects that are queried or |
set are also returned in the map. the following example iterates over the map returned by the getpopulatedfieldsasmap() method after a soql query. account a = new account(); a.name = 'testmapaccount1'; insert a; a = [select id,name from account where id=:a.id]; map<string, object> fieldstovalue = a.getpopulatedfieldsasmap(); for (string fieldname : fieldstovalue.keyset()){ system.debug('field name is ' + fieldname + ', value is ' + fieldstovalue.get(fieldname)); } // example debug statement output: // debug|field name is id, value is 001r0000003eppkiao // debug|field name is name, value is testmapaccount1 this example iterates over the map returned by the getpopulatedfieldsasmap() method after fields on the sobject are explicitly set. account a = new account(); a.name = 'testmapaccount2'; a.phone = '123-4567'; insert a; map<string, object> fieldstovalue = a.getpopulatedfieldsasmap(); for (string fieldname : fieldstovalue.keyset()) { system.debug('field name is ' + fieldname + ', value is ' + fieldstovalue.get(fieldname)); } // example debug statement output: // debug|field name is name, value is testmapaccount2 // debug|field name is phone, value is 123-4567 // debug|field name is id, value is 001r0000003epppiao the following example shows how to use the getpopulatedfieldsasmap() method with related objects. account a = new account(); a.name='testmapaccount3'; insert a; 3328apex reference guide sobject class contact c = new contact(); c.firstname='testcontactfirstname'; c.lastname ='testcontactlastname'; c.accountid = a.id; insert c; c = [select id, contact.firstname, contact.account.name from contact where id=:c.id limit 1]; map<string, object> fieldstovalue = c.getpopulatedfieldsasmap(); // to get the fields on account, get the account object // and call getmappopulatedfieldsasmap() on that object. a = (account)fieldstovalue.get('account'); fieldstovalue = a.getpopulatedfieldsasmap(); for (string fieldname : fieldstovalue.keyset()) { system.debug('field name is ' + fieldname + ', value is ' + fieldstovalue.get(fieldname)); } // example debug statement output: // debug|field name is id, value is 001r0000003eppuiao // debug|field name is name, value is testmapaccount3 versioned behavior changes in api version 39.0 and later, getpopulatedfieldsasmap returns all values set on the sobject, even if values were set after the record was queried. this behavior is dependent on the version of the apex class calling this method and not on the version of the class that generated the sobject. if you query an sobject at api version 20.0, and then call this method in a class with api version 40.0, you will get the full set of fields. getsobject(fieldname) returns the value for the specified field. this method is primarily used with dynamic dml to access values for external ids. signature public sobject getsobject(string fieldname) parameters fieldname type: string return value type: sobject 3329apex reference guide sobject class example account acc = new account(name = 'acme', description = 'acme account'); insert acc; contact con = new contact(lastname = 'acmecon', accountid = acc.id); insert con; sobject contactdb = [select id, accountid, account.name from contact where id = :con.id limit 1]; account a = (account)contactdb.getsobject('account'); system.assertequals('acme', a.name); getsobject(field) returns the value for the field specified by the field token schema.sobjectfield, such as, schema.myobj.myexternalid. this method is primarily used with dynamic dml to access values for external ids. |
signature public sobject getsobject(schema.sobjectfield field) parameters field type: schema.sobjectfield return value type: sobject usage if the method references polymorphic fields, a name object is returned. use the typeof clause in the soql select statement to directly get results that depend on the runtime object type referenced by the polymorphic field. see working with polymorphic relationships in soql queries. example account acc = new account(name = 'acme', description = 'acme account'); insert acc; contact con = new contact(lastname = 'acmecon', accountid = acc.id); insert con; schema.describefieldresult fieldresult = contact.accountid.getdescribe(); schema.sobjectfield field = fieldresult.getsobjectfield(); sobject contactdb = [select id, accountid, account.name from contact where id = :con.id limit 1]; account a = (account)contactdb.getsobject(field); system.assertequals('acme', a.name); 3330apex reference guide sobject class getsobjects(fieldname) returns the values for the specified field. this method is primarily used with dynamic dml to access values for associated objects, such as child relationships. signature public sobject[] getsobjects(string fieldname) parameters fieldname type: string return value type: sobject[] usage for more information, see dynamic dml. example account acc = new account(name = 'acme', description = 'acme account'); insert acc; contact con = new contact(lastname = 'acmecon', accountid = acc.id); insert con; sobject[] a = [select id, (select name from contacts limit 1) from account where id = :acc.id]; sobject[] contactsdb = a.get(0).getsobjects('contacts'); string fieldvalue = (string)contactsdb.get(0).get('name'); system.assertequals('acmecon', fieldvalue); getsobjects(fieldname) returns the value for the field specified by the field token schema.fieldname, such as, schema.account.contact. this method is primarily used with dynamic dml to access values for associated objects, such as child relationships. signature public sobject[] getsobjects(schema.sobjecttype fieldname) parameters fieldname type: schema.sobjecttype return value type: sobject[] 3331apex reference guide sobject class getsobjecttype() returns the token for this sobject. this method is primarily used with describe information. signature public schema.sobjecttype getsobjecttype() return value type: schema.sobjecttype usage for more information, see apex_dynamic_describe_objects_understanding. example account acc = new account(name = 'acme', description = 'acme account'); schema.sobjecttype expected = schema.account.getsobjecttype(); system.assertequals(expected, acc.getsobjecttype()); getquickactionname() retrieves the name of a quick action associated with this sobject. typically used in triggers. signature public string getquickactionname() return value type: string example trigger acctrig2 on contact (before insert) { for (contact c : trigger.new) { if (c.getquickactionname() == quickaction.createcontact) { c.wherefrom__c = 'globaactionl'; } else if (c.getquickactionname() == schema.account.quickaction.createcontact) { c.wherefrom__c = 'accountaction'; } else if (c.getquickactionname() == null) { c.wherefrom__c = 'noaction'; } else { system.assert(false); } } } 3332 |
apex reference guide sobject class haserrors() returns true if an sobject instance has associated errors. the error message can be associated to the sobject instance by using sobject.adderror(), validation rules, or by other means. signature public boolean haserrors() return value type: boolean isclone() returns true if an entity is cloned from something, even if the entity hasn’t been saved. the method can only be used within the transaction where the entity is cloned, as clone information doesn’t persist in subsequent transactions. signature public boolean isclone() return value type: boolean example account acc = new account(name = 'acme'); insert acc; account acc2 = acc.clone(); // test before saving system.assertequals(true, acc2.isclone()); insert acc2; // test after saving system.assertequals(true, acc2.isclone()); isset(fieldname) returns information about the queried sobject field. returns true if the sobject field is populated, either by direct assignment or by inclusion in a soql query. returns false if the sobject field is not set. if an invalid field is specified, an sobjectexception is thrown. signature public void isset(string fieldname) parameters fieldname type: string 3333apex reference guide sobject class return value type: boolean usage the isset method doesn’t check if a field is accessible to a specific user via org permissions or other specialized access permissions. example contact c = new contact(lastname = 'joyce'); system.assertequals(true, c.isset('lastname')); system.assertequals(false, c.isset('firstname')); // firstname field is not written to c.firstname = null; system.assertequals(true, c.isset('firstname')); //firstname field is written to isset(field) returns information about the queried sobject field. returns true if the sobject field is populated, either by direct assignment or by inclusion in a soql query. returns false if the sobject field is not set. if an invalid field is specified, an sobjectexception is thrown. signature public void isset(schema.sobjectfield field) parameters field type:sobjectfield class return value type: boolean usage the isset method doesn’t check if a field is accessible to a specific user via org permissions or other specialized access permissions. example contact newcontact = new contact(lastname = 'joyce'); insert(newcontact); //insert a new contact with last name joyce contact c = [select firstname from contact where id = :newcontact.id]; system.assertequals(true, c.isset(contact.firstname)); //firstname field in query system.assertequals(false, c.isset(contact.lastname)); //lastname field not in query put(fieldname, value) sets the value for the specified field and returns the previous value for the field. 3334apex reference guide sobject class signature public object put(string fieldname, object value) parameters fieldname type: string value type: object return value type: object example account acc = new account(name = 'test', description = 'old desc'); string olddesc = (string)acc.put('description', 'new desc'); system.assertequals('old desc', olddesc); system.assertequals('new desc', acc.description); put(field, value) sets the value for the field specified by the field token schema.sobjectfield, such as, schema.account.accountnumber and returns the previous value for the field. signature public object put(schema.sobjectfield field, object value) parameters field type: schema.sobjectfield value type: object return value type: object example account acc = new account(name = 'test', description = 'old desc'); string olddesc = (string)acc.put(schema.account.description, 'new desc'); system.assertequals('old desc', olddesc); system.assertequals('new desc', acc.description); 3335apex reference guide sobject class note: field tokens aren't available for person accounts. if you access schema.account.fieldname, you get an exception error. instead |
, specify the field name as a string. putsobject(fieldname, value) sets the value for the specified field. this method is primarily used with dynamic dml for setting external ids. the method returns the previous value of the field. signature public sobject putsobject(string fieldname, sobject value) parameters fieldname type: string value type: sobject return value type: sobject example account acc = new account(name = 'acme', description = 'acme account'); insert acc; contact con = new contact(lastname = 'acmecon', accountid = acc.id); insert con; account acc2 = new account(name = 'not acme'); contact contactdb = (contact)[select id, accountid, account.name from contact where id = :con.id limit 1]; account a = (account)contactdb.putsobject('account', acc2); system.assertequals('acme', a.name); system.assertequals('not acme', contactdb.account.name); putsobject(fieldname, value) sets the value for the field specified by the token schema.sobjecttype. this method is primarily used with dynamic dml for setting external ids. the method returns the previous value of the field. signature public sobject putsobject(schema.sobjecttype fieldname, sobject value) parameters fieldname type: schema.sobjecttype 3336apex reference guide sobject class value type: sobject return value type: sobject recalculateformulas() deprecated as of api version 57.0. use the recalculateformulas() method in the system.formula class instead. signature public void recalculateformulas() return value type: void usage this method doesn’t recalculate cross-object formulas. if you call this method on objects that have both cross-object and non-cross-object formula fields, only the non-cross-object formula fields are recalculated. each recalculateformulas call counts against the soql query limits. see execution governors and limits. see also: recalculateformulas(sobjects) what is a cross-object formula? setoptions(dmloptions) sets the dmloptions object for the sobject. signature public void setoptions(database.dmloptions dmloptions) parameters dmloptions type: database.dmloptions return value type: void 3337apex reference guide sobjectaccessdecision class example database.dmloptions dmo = new database.dmloptions(); dmo.assignmentruleheader.usedefaultrule = true; account acc = new account(name = 'acme'); acc.setoptions(dmo); sobjectaccessdecision class contains the results of a call to the security.stripinaccessible method and methods to retrieve those results. namespace system in this section: sobjectaccessdecision methods sobjectaccessdecision methods the following are methods for sobjectaccessdecision. in this section: getmodifiedindexes() returns the indexes of sobjects that are modified by the stripinaccessible method. getrecords() returns a list of new sobjects that are identical to the source records, except that they are stripped of fields that fail the field-level security check for the current user. getremovedfields() returns a map of sobject types to their corresponding inaccessible fields. the map key is a string representation of the sobject type. the map value is a set of strings, which denote the fields names that are inaccessible. getmodifiedindexes() returns the indexes of sobjects that are modified by the stripinaccessible method. signature public set<integer> getmodifiedindexes() return value type: set<integer> a set of unsigned integers that represent the row indexes of the modified sobjects. 3338apex reference guide sobjectaccessdecision class example in this example, the user doesn’t have permission to update the annualrevenue field of an account. list<account> accounts = new list<account>{ new account(name='account1', annualrevenue=1000), new account(name='account2') }; // strip fields that are not updatable sobjectaccessdecision decision = security.stripinaccessible( accesstype.updatable, accounts); |
// print stripped records for (sobject strippedaccount : decision.getrecords()) { system.debug(strippedaccount); } // print modified indexes system.debug(decision.getmodifiedindexes()); getrecords() returns a list of new sobjects that are identical to the source records, except that they are stripped of fields that fail the field-level security check for the current user. usage the stripinaccessible method performs field-level access check for the source records in the context of the current user’s operation. the getrecords() method returns the new records that contain only the fields that the current user has access to. signature public list<sobject> getrecords() return value type: list<sobject> even if the result list contains only one sobject, the return type is still a list (of size one). example in this example, the user doesn’t have permission to update the annualrevenue field of an account. list<account> accounts = new list<account>{ new account(name='account1', annualrevenue=1000), new account(name='account2') }; // strip fields that are not updatable sobjectaccessdecision decision = security.stripinaccessible( accesstype.updatable, 3339apex reference guide staticresourcecalloutmock class accounts); // print stripped records for (sobject strippedaccount : decision.getrecords()) { system.debug(strippedaccount); } getremovedfields() returns a map of sobject types to their corresponding inaccessible fields. the map key is a string representation of the sobject type. the map value is a set of strings, which denote the fields names that are inaccessible. signature public map<string,set<string>> getremovedfields() return value type: map<string,set<string>> example in this example, the user doesn’t have permission to update the annualrevenue field of an account. list<account> accounts = new list<account>{ new account(name='account1', annualrevenue=1000), new account(name='account2') }; // strip fields that are not updatable sobjectaccessdecision decision = security.stripinaccessible( accesstype.updatable, accounts); // print stripped records for (sobject strippedaccount : decision.getrecords()) { system.debug(strippedaccount); } // print removed fields system.debug(decision.getremovedfields()); staticresourcecalloutmock class utility class used to specify a fake response for testing http callouts. namespace system 3340apex reference guide staticresourcecalloutmock class usage use the methods in this class to set the response properties for testing http callouts. in this section: staticresourcecalloutmock constructors staticresourcecalloutmock methods staticresourcecalloutmock constructors the following are constructors for staticresourcecalloutmock. in this section: staticresourcecalloutmock() creates a new instance of the staticresourcecalloutmock class. staticresourcecalloutmock() creates a new instance of the staticresourcecalloutmock class. signature public staticresourcecalloutmock() staticresourcecalloutmock methods the following are methods for staticresourcecalloutmock. all are instance methods. in this section: setheader(headername, headervalue) sets the specified header name and value for the fake response. setstaticresource(resourcename) sets the specified static resource, which contains the response body. setstatus(httpstatus) sets the specified http status for the response. setstatuscode(httpstatuscode) sets the specified http status for the response. setheader(headername, headervalue) sets the specified header name and value for the fake response. signature public void setheader(string headername, string headervalue) 3341apex reference guide staticresourcecalloutmock class parameters headername type: string headervalue type: string return value type: void setstaticresource(resourcename) sets the specified static resource, which contains the response body. signature public void setstaticresource(string resourcename) parameters resourcename type: string return value type: void setstatus(httpstatus) sets the specified http status for the response. signature public void setstatus(string httpstatus) |
parameters httpstatus type: string return value type: void setstatuscode(httpstatuscode) sets the specified http status for the response. 3342apex reference guide string class signature public void setstatuscode(integer httpstatuscode) parameters httpstatuscode type: integer return value type: void string class contains methods for the string primitive data type. namespace system usage for more information on strings, see string data type. string methods the following are methods for string. in this section: abbreviate(maxwidth) returns an abbreviated version of the string, of the specified length and with ellipses appended if the current string is longer than the specified length; otherwise, returns the original string without ellipses. abbreviate(maxwidth, offset) returns an abbreviated version of the string, starting at the specified character offset and of the specified length. the returned string has ellipses appended at the start and the end if characters have been removed at these locations. capitalize() returns the current string with the first letter changed to title case. center(size) returns a version of the current string of the specified size padded with spaces on the left and right, so that it appears in the center. if the specified size is smaller than the current string size, the entire string is returned without added spaces. center(size, paddingstring) returns a version of the current string of the specified size padded with the specified string on the left and right, so that it appears in the center. if the specified size is smaller than the current string size, the entire string is returned without padding. charat(index) returns the value of the character at the specified index. 3343apex reference guide string class codepointat(index) returns the unicode code point value at the specified index. codepointbefore(index) returns the unicode code point value that occurs before the specified index. codepointcount(beginindex, endindex) returns the number of unicode code points within the specified text range. compareto(secondstring) compares two strings lexicographically, based on the unicode value of each character in the strings. contains(substring) returns true if and only if the string that called the method contains the specified sequence of characters in substring. containsany(inputstring) returns true if the current string contains any of the characters in the specified string; otherwise, returns false. containsignorecase(substring) returns true if the current string contains the specified sequence of characters without regard to case; otherwise, returns false. containsnone(inputstring) returns true if the current string doesn’t contain any of the characters in the specified string; otherwise, returns false. containsonly(inputstring) returns true if the current string contains characters only from the specified sequence of characters and not any other characters; otherwise, returns false. containswhitespace() returns true if the current string contains any white space characters; otherwise, returns false. countmatches(substring) returns the number of times the specified substring occurs in the current string. deletewhitespace() returns a version of the current string with all white space characters removed. difference(secondstring) returns the difference between the current string and the specified string. endswith(suffix) returns true if the string that called the method ends with the specified suffix. endswithignorecase(suffix) returns true if the current string ends with the specified suffix; otherwise, returns false. equals(secondstring) deprecated. this method is replaced by equals(stringorid). returns true if the passed-in string is not null and represents the same binary sequence of characters as the current string. use this method to perform case-sensitive comparisons. equals(stringorid) returns true if the passed-in object is not null and represents the same binary sequence of characters as the current string. use this method to compare a string to an object that represents a string or an id. equalsignorecase(secondstring) returns true if the secondstring isn’t null and represents the same sequence of characters as the string that called the method, ignoring case. 3344apex reference guide string class escapecsv() returns a string for a csv column enclosed in double quotes, if required. escapeecmascript() escapes the characters in the string using ecmascript string rules. escapehtml3() escapes the characters in a string using html 3.0 entities. escapeh |
tml4() escapes the characters in a string using html 4.0 entities. escapejava() returns a string whose characters are escaped using java string rules. characters escaped include quotes and control characters, such as tab, backslash, and carriage return characters. escapesinglequotes(stringtoescape) returns a string with the escape character (\) added before any single quotation marks in the string s. escapeunicode() returns a string whose unicode characters are escaped to a unicode escape sequence. escapexml() escapes the characters in a string using xml entities. format(stringtoformat, formattingarguments) treat the first argument as a pattern and return a string using the second argument for substitution and formatting. the substitution and formatting are the same as apex:outputtext and the java messageformat class. non-string types in the second argument’s list are implicitly converted to strings, respecting the tostring() method overrides that exist on the type. fromchararray(chararray) returns a string from the values of the list of integers. getchars() returns an array of character values that represent the characters in this string. getcommonprefix(strings) returns the initial sequence of characters as a string that is common to all the specified strings. getlevenshteindistance(stringtocompare) returns the levenshtein distance between the current string and the specified string. getlevenshteindistance(stringtocompare, threshold) returns the levenshtein distance between the current string and the specified string if it is less than or equal than the given threshold; otherwise, returns -1. hashcode() returns a hash code value for this string. indexof(substring) returns the index of the first occurrence of the specified substring. if the substring does not occur, this method returns -1. indexof(substring, index) returns the zero-based index of the first occurrence of the specified substring from the point of the given index. if the substring does not occur, this method returns -1. 3345apex reference guide string class indexofany(substring) returns the zero-based index of the first occurrence of any character specified in the substring. if none of the characters occur, returns -1. indexofanybut(substring) returns the zero-based index of the first occurrence of a character that is not in the specified substring. otherwise, returns -1. indexofchar(character) returns the index of the first occurrence of the character that corresponds to the specified character value. indexofchar(character, startindex) returns the index of the first occurrence of the character that corresponds to the specified character value, starting from the specified index. indexofdifference(stringtocompare) returns the zero-based index of the character where the current string begins to differ from the specified string. indexofignorecase(substring) returns the zero-based index of the first occurrence of the specified substring without regard to case. if the substring does not occur, this method returns -1. indexofignorecase(substring, startposition) returns the zero-based index of the first occurrence of the specified substring from the point of index i, without regard to case. if the substring does not occur, this method returns -1. isalllowercase() returns true if all characters in the current string are lowercase; otherwise, returns false. isalluppercase() returns true if all characters in the current string are uppercase; otherwise, returns false. isalpha() returns true if all characters in the current string are unicode letters only; otherwise, returns false. isalphaspace() returns true if all characters in the current string are unicode letters or spaces only; otherwise, returns false. isalphanumeric() returns true if all characters in the current string are unicode letters or numbers only; otherwise, returns false. isalphanumericspace() returns true if all characters in the current string are unicode letters, numbers, or spaces only; otherwise, returns false. isasciiprintable() returns true if the current string contains only ascii printable characters; otherwise, returns false. isblank(inputstring) returns true if the specified string is white space, empty (''), or null; otherwise, returns false. isempty(inputstring) returns true if the specified string is empty ('') or null; otherwise, returns false. isnotblank(inputstring) returns true if the specified string is not whitespace, not empty (''), and not null; otherwise, returns false. |
isnotempty(inputstring) returns true if the specified string is not empty ('') and not null; otherwise, returns false. 3346apex reference guide string class isnumeric() returns true if the current string contains only unicode digits; otherwise, returns false. isnumericspace() returns true if the current string contains only unicode digits or spaces; otherwise, returns false. iswhitespace() returns true if the current string contains only white space characters or is empty; otherwise, returns false. join(iterableobj, separator) joins the elements of the specified iterable object, such as a list, into a single string separated by the specified separator. lastindexof(substring) returns the index of the last occurrence of the specified substring. if the substring does not occur, this method returns -1. lastindexof(substring, endposition) returns the index of the last occurrence of the specified substring, starting from the character at index 0 and ending at the specified index. lastindexofchar(character) returns the index of the last occurrence of the character that corresponds to the specified character value. lastindexofchar(character, endindex) returns the index of the last occurrence of the character that corresponds to the specified character value, starting from the specified index. lastindexofignorecase(substring) returns the index of the last occurrence of the specified substring regardless of case. lastindexofignorecase(substring, endposition) returns the index of the last occurrence of the specified substring regardless of case, starting from the character at index 0 and ending at the specified index. left(length) returns the leftmost characters of the current string of the specified length. leftpad(length) returns the current string padded with spaces on the left and of the specified length. leftpad(length, padstr) returns the current string padded with string padstr on the left and of the specified length. length() returns the number of 16-bit unicode characters contained in the string. mid(startindex, length) returns a new string that begins with the character at the specified zero-based startindex with the number of characters specified by length. normalizespace() returns the current string with leading, trailing, and repeating white space characters removed. offsetbycodepoints(index, codepointoffset) returns the index of the unicode code point that is offset by the specified number of code points, starting from the given index. remove(substring) removes all occurrences of the specified substring and returns the string result. 3347apex reference guide string class removeend(substring) removes the specified substring only if it occurs at the end of the string. removeendignorecase(substring) removes the specified substring only if it occurs at the end of the string using a case-insensitive match. removestart(substring) removes the specified substring only if it occurs at the beginning of the string. removestartignorecase(substring) removes the specified substring only if it occurs at the beginning of the string using a case-insensitive match. repeat(numberoftimes) returns the current string repeated the specified number of times. repeat(separator, numberoftimes) returns the current string repeated the specified number of times using the specified separator to separate the repeated strings. replace(target, replacement) replaces each substring of a string that matches the literal target sequence target with the specified literal replacement sequence replacement. replaceall(regexp, replacement) replaces each substring of a string that matches the regular expression regexp with the replacement sequence replacement. replacefirst(regexp, replacement) replaces the first substring of a string that matches the regular expression regexp with the replacement sequence replacement. reverse() returns a string with all the characters reversed. right(length) returns the rightmost characters of the current string of the specified length. rightpad(length) returns the current string padded with spaces on the right and of the specified length. rightpad(length, padstr) returns the current string padded with string padstr on the right and of the specified length. 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. 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. splitbycharactertype() splits the current string by character type and returns a |
list of contiguous character groups of the same type as complete tokens. 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. startswith(prefix) returns true if the string that called the method begins with the specified prefix. 3348apex reference guide string class startswithignorecase(prefix) returns true if the current string begins with the specified prefix regardless of the prefix case. striphtmltags() removes html markup and returns plain text. 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. 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. substringafter(separator) returns the substring that occurs after the first occurrence of the specified separator. substringafterlast(separator) returns the substring that occurs after the last occurrence of the specified separator. substringbefore(separator) returns the substring that occurs before the first occurrence of the specified separator. substringbeforelast(separator) returns the substring that occurs before the last occurrence of the specified separator. substringbetween(tag) returns the substring that occurs between two instances of the specified tag string. substringbetween(open, close) returns the substring that occurs between the two specified strings. swapcase() swaps the case of all characters and returns the resulting string by using the default (english us) locale. tolowercase() converts all of the characters in the string to lowercase using the rules of the default (english us) locale. tolowercase(locale) converts all of the characters in the string to lowercase using the rules of the specified locale. touppercase() converts all of the characters in the string to uppercase using the rules of the default (english us) locale. touppercase(locale) converts all of the characters in the string to the uppercase using the rules of the specified locale. trim() returns a copy of the string that no longer contains any leading or trailing white space characters. uncapitalize() returns the current string with the first letter in lowercase. unescapecsv() returns a string representing an unescaped csv column. unescapeecmascript() unescapes any ecmascript literals found in the string. 3349apex reference guide string class unescapehtml3() unescapes the characters in a string using html 3.0 entities. unescapehtml4() unescapes the characters in a string using html 4.0 entities. 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). unescapeunicode() returns a string whose escaped unicode characters are unescaped. unescapexml() unescapes the characters in a string using xml entities. valueof(datetoconvert) returns a string that represents the specified date in the standard “yyyy-mm-dd” format. 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. valueof(decimaltoconvert) returns a string that represents the specified decimal. valueof(doubletoconvert) returns a string that represents the specified double. valueof(integertoconvert) returns a string that represents the specified integer. valueof(longtoconvert) returns a string that represents the specified long. valueof(toconvert) returns a string representation of the specified object argument. 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. abbreviate(maxwidth) returns an abbreviated version of the string, of the specified length and with ellipses appended if the current string is longer than the specified length |
; otherwise, returns the original string without ellipses. signature public string abbreviate(integer maxwidth) parameters maxwidth type: integer if maxwidth is less than four, this method throws a run-time exception. 3350apex reference guide string class return value type: string example string s = 'hello maximillian'; string s2 = s.abbreviate(8); system.assertequals('hello...', s2); system.assertequals(8, s2.length()); abbreviate(maxwidth, offset) returns an abbreviated version of the string, starting at the specified character offset and of the specified length. the returned string has ellipses appended at the start and the end if characters have been removed at these locations. signature public string abbreviate(integer maxwidth, integer offset) parameters maxwidth type: integer note that the offset is not necessarily the leftmost character in the returned string or the first character following the ellipses, but it appears somewhere in the result. regardless, abbreviate won’t return a string of length greater than maxwidth.if maxwidth is too small, this method throws a run-time exception. offset type: integer return value type: string example string s = 'hello maximillian'; // start at m string s2 = s.abbreviate(9,6); system.assertequals('...max...', s2); system.assertequals(9, s2.length()); capitalize() returns the current string with the first letter changed to title case. signature public string capitalize() 3351apex reference guide string class return value type: string usage this method is based on the character.totitlecase(char) java method. example string s = 'hello maximillian'; string s2 = s.capitalize(); system.assertequals('hello maximillian', s2); center(size) returns a version of the current string of the specified size padded with spaces on the left and right, so that it appears in the center. if the specified size is smaller than the current string size, the entire string is returned without added spaces. signature public string center(integer size) parameters size type: integer return value type: string example string s = 'hello'; string s2 = s.center(9); system.assertequals( ' hello ', s2); center(size, paddingstring) returns a version of the current string of the specified size padded with the specified string on the left and right, so that it appears in the center. if the specified size is smaller than the current string size, the entire string is returned without padding. signature public string center(integer size, string paddingstring) 3352apex reference guide string class parameters size type: integer paddingstring type: string return value type: string example string s = 'hello'; string s2 = s.center(9, '-'); system.assertequals('--hello--', s2); charat(index) returns the value of the character at the specified index. signature public integer charat(integer index) parameters index type: integer the index of the character to get the value of. return value type: integer the integer value of the character. usage the charat method returns the value of the character pointed to by the specified index. if the index points to the beginning of a surrogate pair (the high-surrogate code point), this method returns only the high-surrogate code point. to return the supplementary code point corresponding to a surrogate pair, call codepointat instead. example this example gets the value of the first character at index 0. string str = 'ω is omega.'; system.assertequals(937, str.charat(0)); 3353apex reference guide string class this example shows the difference between charat and codepointat. the example calls these methods on escaped supplementary unicode characters. charat(0) returns the high surrogate value, which corresponds to \ud835. codepointat(0) returns the value for the entire surrogate pair. string str = '\ud835\udd0a'; system.assertequals(55349, str.charat(0), 'charat(0) didn\'t return the high surrogate.'); system.assertequals(120074, str. |
codepointat(0), 'codepointat(0) didn\'t return the entire two-character supplementary value.'); codepointat(index) returns the unicode code point value at the specified index. signature public integer codepointat(integer index) parameters index type: integer the index of the characters (unicode code units) in the string. the index range is from zero to the string length minus one. return value type: integer the unicode code point value at the specified index. usage if the index points to the beginning of a surrogate pair (the high-surrogate code point), and the character value at the following index points to the low-surrogate code point, this method returns the supplementary code point corresponding to this surrogate pair. otherwise, this method returns the character value at the given index. for more information on unicode and surrogate pairs, see the unicode consortium. example this example gets the code point value of the first character at index 0, which is the escaped omega character. also, the example gets the code point at index 20, which corresponds to the escaped supplementary unicode characters (a pair of characters). finally, it verifies that the escaped and unescaped forms of omega have the same code point values. the supplementary characters in this example (\\ud835\\udd0a) correspond to mathematical fraktur capital g: string str = '\u03a9 is ω (omega), and \ud835\udd0a ' + ' is fraktur capital g.'; system.assertequals(937, str.codepointat(0)); system.assertequals(120074, str.codepointat(20)); // escaped or unescaped forms of the same character have the same code point system.assertequals(str.codepointat(0), str.codepointat(5)); 3354apex reference guide string class codepointbefore(index) returns the unicode code point value that occurs before the specified index. signature public integer codepointbefore(integer index) parameters index type: integer the index before the unicode code point that is to be returned. the index range is from one to the string length. return value type: integer the character or unicode code point value that occurs before the specified index. usage if the character value at index-1 is the low-surrogate code point, and index-2 is not negative and the character at this index location is the high-surrogate code point, this method returns the supplementary code point corresponding to this surrogate pair. if the character value at index-1 is an unpaired low-surrogate or high-surrogate code point, the surrogate value is returned. for more information on unicode and surrogate pairs, see the unicode consortium. example this example gets the code point value of the first character (before index 1), which is the escaped omega character. also, the example gets the code point at index 20, which corresponds to the escaped supplementary characters (the two characters before index 22). string str = '\u03a9 is ω (omega), and \ud835\udd0a ' + ' is fraktur capital g.'; system.assertequals(937, str.codepointbefore(1)); system.assertequals(120074, str.codepointbefore(22)); codepointcount(beginindex, endindex) returns the number of unicode code points within the specified text range. signature public integer codepointcount(integer beginindex, integer endindex) parameters beginindex type: integer the index of the first character in the range. 3355apex reference guide string class endindex type: integer the index after the last character in the range. return value type: integer the number of unicode code points within the specified range. usage the specified range begins at beginindex and ends at endindex—1. unpaired surrogates within the text range count as one code point each. example this example writes the count of code points in a substring that contains an escaped unicode character and another substring that contains unicode supplementary characters, which count as one code point. string str = '\u03a9 and \ud835\udd0a characters.'; system.debug('count of code points for ' + str.substring(0,1) + ': ' + str.codepointcount(0,1)); system.debug('count of code points for ' + str.substring(6,8) |
+ ': ' + str.codepointcount(6,8)); // output: // count of code points for ω: 1 // count of code points for (cid:0)(cid:0): 1 compareto(secondstring) compares two strings lexicographically, based on the unicode value of each character in the strings. signature public integer compareto(string secondstring) parameters secondstring type: string return value type: integer usage the result is: • a negative integer if the string that called the method lexicographically precedes secondstring 3356apex reference guide string class • a positive integer if the string that called the method lexicographically follows compsecondstringstring • zero if the strings are equal if there is no index position at which the strings differ, then the shorter string lexicographically precedes the longer string. note that this method returns 0 whenever the equals method returns true. example string mystring1 = 'abcde'; string mystring2 = 'abcd'; integer result = mystring1.compareto(mystring2); system.assertequals(result, 1); contains(substring) returns true if and only if the string that called the method contains the specified sequence of characters in substring. signature public boolean contains(string substring) parameters substring type: string return value type: boolean example string mystring1 = 'abcde'; string mystring2 = 'abcd'; boolean result = mystring1.contains(mystring2); system.assertequals(result, true); containsany(inputstring) returns true if the current string contains any of the characters in the specified string; otherwise, returns false. signature public boolean containsany(string inputstring) parameters inputstring type: string 3357apex reference guide string class return value type: boolean example string s = 'hello'; boolean b1 = s.containsany('hx'); boolean b2 = s.containsany('x'); system.assertequals(true, b1); system.assertequals(false, b2); containsignorecase(substring) returns true if the current string contains the specified sequence of characters without regard to case; otherwise, returns false. signature public boolean containsignorecase(string substring) parameters substring type: string return value type: boolean example string s = 'hello'; boolean b = s.containsignorecase('he'); system.assertequals( true, b); containsnone(inputstring) returns true if the current string doesn’t contain any of the characters in the specified string; otherwise, returns false. signature public boolean containsnone(string inputstring) parameters inputstring type: string if inputstring is an empty string or the current string is empty, this method returns true. if inputstring is null, this method returns a run-time exception. 3358apex reference guide string class return value type: boolean example string s1 = 'abcde'; system.assert(s1.containsnone('fg')); containsonly(inputstring) returns true if the current string contains characters only from the specified sequence of characters and not any other characters; otherwise, returns false. signature public boolean containsonly(string inputstring) parameters inputstring type: string return value type: boolean example string s1 = 'abba'; string s2 = 'abba xyz'; boolean b1 = s1.containsonly('abcd'); system.assertequals( true, b1); boolean b2 = s2.containsonly('abcd'); system.assertequals( false, b2); containswhitespace() returns true if the current string contains any white space characters; otherwise, returns false. signature public boolean containswhitespace() 3359apex reference guide string class return value type: boolean example string s = 'hello jane'; system.assert(s.containswhitespace()); //true s = 'hellojane '; system.assert(s.containswhitespace()); //true s = ' hellojane'; system.assert(s.containswhitespace()); //true s = 'hellojane'; system.assert(!s.containswh |
itespace()); //false countmatches(substring) returns the number of times the specified substring occurs in the current string. signature public integer countmatches(string substring) parameters substring type: string return value type: integer example string s = 'hello jane'; system.assertequals(1, s.countmatches('hello')); s = 'hello hello'; system.assertequals(2, s.countmatches('hello')); s = 'hello hello'; system.assertequals(1, s.countmatches('hello')); deletewhitespace() returns a version of the current string with all white space characters removed. signature public string deletewhitespace() return value type: string 3360apex reference guide string class example string s1 = ' hello jane '; string s2 = 'hellojane'; system.assertequals(s2, s1.deletewhitespace()); difference(secondstring) returns the difference between the current string and the specified string. signature public string difference(string secondstring) parameters secondstring type: string if secondstring is an empty string, this method returns an empty string.if secondstring is null, this method throws a run-time exception. return value type: string example string s = 'hello jane'; string d1 = s.difference('hello max'); system.assertequals( 'max', d1); string d2 = s.difference('goodbye'); system.assertequals( 'goodbye', d2); endswith(suffix) returns true if the string that called the method ends with the specified suffix. signature public boolean endswith(string suffix) parameters suffix type: string 3361apex reference guide string class return value type: boolean example string s = 'hello jason'; system.assert(s.endswith('jason')); endswithignorecase(suffix) returns true if the current string ends with the specified suffix; otherwise, returns false. signature public boolean endswithignorecase(string suffix) parameters suffix type: string return value type: boolean example string s = 'hello jason'; system.assert(s.endswithignorecase('jason')); equals(secondstring) deprecated. this method is replaced by equals(stringorid). returns true if the passed-in string is not null and represents the same binary sequence of characters as the current string. use this method to perform case-sensitive comparisons. signature public boolean equals(string secondstring) parameters secondstring type: string return value type: boolean 3362apex reference guide string class usage this method returns true when the compareto method returns 0. use this method to perform case-sensitive comparisons. in contrast, the == operator performs case-insensitive string comparisons to match apex semantics. example string mystring1 = 'abcde'; string mystring2 = 'abcd'; boolean result = mystring1.equals(mystring2); system.assertequals(result, false); equals(stringorid) returns true if the passed-in object is not null and represents the same binary sequence of characters as the current string. use this method to compare a string to an object that represents a string or an id. signature public boolean equals(object stringorid) parameters stringorid type: object return value type: boolean usage if you compare id values, the lengths of ids don’t need to be equal. for example, if you compare a 15-character id string to an object that represents the equivalent 18-character id value, this method returns true. for more information about 15-character and 18-character ids, see the id data type. use this method to perform case-sensitive comparisons. in contrast, the == operator performs case-insensitive string comparisons to match apex semantics. example these examples show comparisons between different types of variables with both equal and unequal values. the examples also show how apex automatically converts certain values before comparing them. // compare a string to an object containing a string object obj1 = 'abc'; string str = 'abc'; boolean result1 = str.equals(obj1); system.assertequals(true, result1); // compare a string to an object containing a number 3363apex reference guide string class integer obj |
2 = 100; boolean result2 = str.equals(obj2); system.assertequals(false, result2); // compare a string to an id of the same length. // 15-character id id idvalue15 = '001d000000ju1zh'; // 15-character id string value string stringvalue15 = '001d000000ju1zh'; boolean result3 = stringvalue15.equals(idvalue15); system.assertequals(true, result3); // compare two equal id values of different lengths: // 15-character id and 18-character id id idvalue18 = '001d000000ju1zhiar'; boolean result4 = stringvalue15.equals(idvalue18); system.assertequals(true, result4); equalsignorecase(secondstring) returns true if the secondstring isn’t null and represents the same sequence of characters as the string that called the method, ignoring case. signature public boolean equalsignorecase(string secondstring) parameters secondstring type: string return value type: boolean usage the string.equalsignorecase() method ignores the locale of the context user. if you want the string comparison to be performed according to the locale, use the == operator instead. the string.equalsignorecase() method typically executes faster than the operator because the method ignores the locale. example string mystring1 = 'abcd'; string mystring2 = 'abcd'; boolean result = mystring1.equalsignorecase(mystring2); system.assertequals(result, true); 3364apex reference guide string class escapecsv() returns a string for a csv column enclosed in double quotes, if required. signature public string escapecsv() return value type: string usage if the string contains a comma, newline or double quote, the returned string is enclosed in double quotes. also, any double quote characters in the string are escaped with another double quote. if the string doesn’t contain a comma, newline or double quote, it is returned unchanged. example string s1 = 'max1, "max2"'; string s2 = s1.escapecsv(); system.assertequals('"max1, ""max2"""', s2); escapeecmascript() escapes the characters in the string using ecmascript string rules. signature public string escapeecmascript() return value type: string usage the only difference between apex strings and ecmascript strings is that in ecmascript, a single quote and forward-slash (/) are escaped. example string s1 = '"grade": 3.9/4.0'; string s2 = s1.escapeecmascript(); system.debug(s2); // output is: // \"grade\": 3.9\/4.0 system.assertequals( '\\"grade\\": 3.9\\/4.0', s2); 3365apex reference guide string class escapehtml3() escapes the characters in a string using html 3.0 entities. signature public string escapehtml3() return value type: string example string s1 = '"<black&white>"'; string s2 = s1.escapehtml3(); system.debug(s2); // output: // "<black& // white>" escapehtml4() escapes the characters in a string using html 4.0 entities. signature public string escapehtml4() return value type: string example string s1 = '"<black&white>"'; string s2 = s1.escapehtml4(); system.debug(s2); // output: // "<black& // white>" escapejava() returns a string whose characters are escaped using java string rules. characters escaped include quotes and control characters, such as tab, backslash, and carriage return characters. 3366apex reference guide string class signature public string escapejava() return value type: string the escaped string. example // input string contains quotation marks string s = 'company: "salesforce.com"'; string escapedstr = s.escapejava(); // output string has the quotes escpaded system. |
assertequals('company: \\"salesforce.com\\"', escapedstr); escapesinglequotes(stringtoescape) returns a string with the escape character (\) added before any single quotation marks in the string s. signature public static string escapesinglequotes(string stringtoescape) parameters stringtoescape type: string return value type: string usage this method is useful when creating a dynamic soql statement, to help prevent soql injection. for more information on dynamic soql, see dynamic soql. example string s = '\'hello jason\''; system.debug(s); // outputs 'hello jason' string escapedstr = string.escapesinglequotes(s); // outputs \'hello jason\' system.debug(escapedstr); // escapes the string \\\' to string \' system.assertequals('\\\'hello jason\\\'', escapedstr); 3367apex reference guide string class escapeunicode() returns a string whose unicode characters are escaped to a unicode escape sequence. signature public string escapeunicode() return value type: string the escaped string. example string s = 'de onde você é?'; string escapedstr = s.escapeunicode(); system.assertequals('de onde voc\\u00ea \\u00e9?', escapedstr); escapexml() escapes the characters in a string using xml entities. signature public string escapexml() return value type: string usage supports only the five basic xml entities (gt, lt, quot, amp, apos). does not support dtds or external entities. unicode characters greater than 0x7f are not escaped. example string s1 = '"<black&white>"'; string s2 = s1.escapexml(); system.debug(s2); // output: // "<black& // white>" 3368apex reference guide string class format(stringtoformat, formattingarguments) treat the first argument as a pattern and return a string using the second argument for substitution and formatting. the substitution and formatting are the same as apex:outputtext and the java messageformat class. non-string types in the second argument’s list are implicitly converted to strings, respecting the tostring() method overrides that exist on the type. signature public static string format(string stringtoformat, list<object> formattingarguments) parameters stringtoformat type: string formattingarguments type: list<object> return value type: string versioned behavior changes from version 51.0 and later, the format() method supports single quotes in the stringtoformat parameter and returns a formatted string using the formattingarguments parameter. in version 50.0 and earlier, single quotes weren’t supported. example string template = '{0} was last updated {1}'; list<object> parameters = new list<object> {'universal containers', datetime.newinstance(2018, 11, 15) }; string formatted = string.format(template, parameters); system.debug ('newly formatted string is:' + formatted); fromchararray(chararray) returns a string from the values of the list of integers. signature public static string fromchararray(list<integer> chararray) parameters chararray type: list<integer> return value type: string 3369apex reference guide string class example list<integer> chararr= new integer[]{74}; string convertedchar = string.fromchararray(chararr); system.assertequals('j', convertedchar); getchars() returns an array of character values that represent the characters in this string. signature public list<integer> getchars() return value type: list<integer> a list of integers, each corresponding to a character value in the string. example this sample converts a string to a character array and then gets the first array element, which corresponds to the value of 'j'. string str = 'jane goes fishing.'; integer[] chars = str.getchars(); // get the value of 'j' system.assertequals(74, chars[0]); getcommonprefix(strings) returns the initial sequence of characters as a string that is common to all the specified strings. signature public static string getcommonprefix(list<string> strings) parameters strings |
type: list<string> return value type: string example list<string> ls = new list<string>{'sfdcapex', 'sfdcvisualforce'}; string prefix = string.getcommonprefix(ls); system.assertequals('sfdc', prefix); 3370apex reference guide string class getlevenshteindistance(stringtocompare) returns the levenshtein distance between the current string and the specified string. signature public integer getlevenshteindistance(string stringtocompare) parameters stringtocompare type: string return value type: integer usage the levenshtein distance is the number of changes needed to change one string into another. each change is a single character modification (deletion, insertion or substitution). example string s = 'hello joe'; integer i = s.getlevenshteindistance('hello max'); system.assertequals(3, i); getlevenshteindistance(stringtocompare, threshold) returns the levenshtein distance between the current string and the specified string if it is less than or equal than the given threshold; otherwise, returns -1. signature public integer getlevenshteindistance(string stringtocompare, integer threshold) parameters stringtocompare type: string threshold type: integer return value type: integer 3371apex reference guide string class usage the levenshtein distance is the number of changes needed to change one string into another. each change is a single character modification (deletion, insertion or substitution). example: in this example, the levenshtein distance is 3, but the threshold argument is 2, which is less than the distance, so this method returns -1. example string s = 'hello jane'; integer i = s.getlevenshteindistance('hello max', 2); system.assertequals(-1, i); hashcode() returns a hash code value for this string. signature public integer hashcode() return value type: integer usage this value is based on the hash code computed by the java string.hashcode counterpart method. you can use this method to simplify the computation of a hash code for a custom type that contains string member variables. you can compute your type’s hash code value based on the hash code of each string variable. for example: for more details about the use of hash code methods with custom types, see using custom types in map keys and sets. example public class mycustomclass { string x,y; // provide a custom hash code public integer hashcode() { return (31*x.hashcode())^(y.hashcode()); } } indexof(substring) returns the index of the first occurrence of the specified substring. if the substring does not occur, this method returns -1. 3372apex reference guide string class signature public integer indexof(string substring) parameters substring type: string return value type: integer example string mystring1 = 'abcde'; string mystring2 = 'cd'; integer result = mystring1.indexof(mystring2); system.assertequals(2, result); indexof(substring, index) returns the zero-based index of the first occurrence of the specified substring from the point of the given index. if the substring does not occur, this method returns -1. signature public integer indexof(string substring, integer index) parameters substring type: string index type: integer return value type: integer example string mystring1 = 'abcdabcd'; string mystring2 = 'ab'; integer result = mystring1.indexof(mystring2, 1); system.assertequals(4, result); indexofany(substring) returns the zero-based index of the first occurrence of any character specified in the substring. if none of the characters occur, returns -1. 3373apex reference guide string class signature public integer indexofany(string substring) parameters substring type: string return value type: integer example string s1 = 'abcd'; string s2 = 'xc'; integer result = s1.indexofany(s2); system.assertequals(2, result); indexofanybut(substring) returns the zero-based index of the first occurrence of a character that is not in |
the specified substring. otherwise, returns -1. signature public integer indexofanybut(string substring) parameters substring type: string return value type: integer example string s1 = 'abcd'; string s2 = 'xc'; integer result = s1.indexofanybut(s2); system.assertequals(0, result); indexofchar(character) returns the index of the first occurrence of the character that corresponds to the specified character value. signature public integer indexofchar(integer character) 3374apex reference guide string class parameters character type: integer the integer value of the character in the string. return value type: integer the index of the first occurrence of the specified character, -1 if the character is not found. usage the index that this method returns is in unicode code units. example string str = '\\u03a9 is ω (omega)'; // returns 0, which is the first character. system.debug('indexofchar(937)=' + str.indexofchar(937)); // output: // indexofchar(937)=0 indexofchar(character, startindex) returns the index of the first occurrence of the character that corresponds to the specified character value, starting from the specified index. signature public integer indexofchar(integer character, integer startindex) parameters character type: integer the integer value of the character to look for. startindex type: integer the index to start the search from. return value type: integer the index, starting from the specified start index, of the first occurrence of the specified character, -1 if the character is not found. 3375apex reference guide string class usage the index that this method returns is in unicode code units. example this example shows different ways of searching for the index of the omega character. the first call to indexofchar doesn’t specify a start index and therefore the returned index is 0, which is the first occurrence of omega in the entire string. the subsequent calls specify a start index to find the occurrence of omega in substrings that start at the specified index. string str = 'ω and \\u03a9 and ω'; system.debug('indexofchar(937)=' + str.indexofchar(937)); system.debug('indexofchar(937,1)=' + str.indexofchar(937,1)); system.debug('indexofchar(937,10)=' + str.indexofchar(937,10)); // output: // indexofchar(937)=0 // indexofchar(937,1)=6, (corresponds to the escaped form \\u03a9) // indexofchar(937,10)=12 indexofdifference(stringtocompare) returns the zero-based index of the character where the current string begins to differ from the specified string. signature public integer indexofdifference(string stringtocompare) parameters stringtocompare type: string return value type: integer example string s1 = 'abcd'; string s2 = 'abxc'; integer result = s1.indexofdifference(s2); system.assertequals(2, result); indexofignorecase(substring) returns the zero-based index of the first occurrence of the specified substring without regard to case. if the substring does not occur, this method returns -1. signature public integer indexofignorecase(string substring) 3376apex reference guide string class parameters substring type: string return value type: integer example string s1 = 'abcd'; string s2 = 'bc'; integer result = s1.indexofignorecase(s2, 0); system.assertequals(1, result); indexofignorecase(substring, startposition) returns the zero-based index of the first occurrence of the specified substring from the point of index i, without regard to case. if the substring does not occur, this method returns -1. signature public integer indexofignorecase(string substring, integer startposition) parameters substring type: string startposition type: integer return value type: integer isalllowercase() returns true if all characters in the current string are lowercase; otherwise, returns false. signature public boolean isalllowercase() return value type |
: boolean 3377apex reference guide string class example string alllower = 'abcde'; system.assert(alllower.isalllowercase()); isalluppercase() returns true if all characters in the current string are uppercase; otherwise, returns false. signature public boolean isalluppercase() return value type: boolean example string allupper = 'abcde'; system.assert(allupper.isalluppercase()); isalpha() returns true if all characters in the current string are unicode letters only; otherwise, returns false. signature public boolean isalpha() return value type: boolean example // letters only string s1 = 'abc'; // returns true boolean b1 = s1.isalpha(); system.assertequals( true, b1); // letters and numbers string s2 = 'abc 21'; // returns false boolean b2 = s2.isalpha(); system.assertequals( false, b2); 3378apex reference guide string class isalphaspace() returns true if all characters in the current string are unicode letters or spaces only; otherwise, returns false. signature public boolean isalphaspace() return value type: boolean example string alphaspace = 'aa bb'; system.assert(alphaspace.isalphaspace()); string notalphaspace = 'ab 12'; system.assert(!notalphaspace.isalphaspace()); notalphaspace = 'aa$bb'; system.assert(!notalphaspace.isalphaspace()); isalphanumeric() returns true if all characters in the current string are unicode letters or numbers only; otherwise, returns false. signature public boolean isalphanumeric() return value type: boolean example // letters only string s1 = 'abc'; // returns true boolean b1 = s1.isalphanumeric(); system.assertequals( true, b1); // letters and numbers string s2 = 'abc021'; // returns true boolean b2 = s2.isalphanumeric(); system.assertequals( true, b2); 3379apex reference guide string class isalphanumericspace() returns true if all characters in the current string are unicode letters, numbers, or spaces only; otherwise, returns false. signature public boolean isalphanumericspace() return value type: boolean example string alphanumspace = 'ae 86'; system.assert(alphanumspace.isalphanumericspace()); string notalphanumspace = 'aa$12'; system.assert(!notalphanumspace.isalphaspace()); isasciiprintable() returns true if the current string contains only ascii printable characters; otherwise, returns false. signature public boolean isasciiprintable() return value type: boolean example string ascii = 'abcd1234!@#$%^&*()`~-_+={[}]|:<,>.?'; system.assert(ascii.isasciiprintable()); string notascii = '√'; system.assert(!notascii.isasciiprintable()); isblank(inputstring) returns true if the specified string is white space, empty (''), or null; otherwise, returns false. signature public static boolean isblank(string inputstring) parameters inputstring type: string 3380apex reference guide string class return value type: boolean example string blank = ''; string nullstring = null; string whitespace = ' '; system.assert(string.isblank(blank)); system.assert(string.isblank(nullstring)); system.assert(string.isblank(whitespace)); string alpha = 'hello'; system.assert(!string.isblank(alpha)); isempty(inputstring) returns true if the specified string is empty ('') or null; otherwise, returns false. signature public static boolean isempty(string inputstring) parameters inputstring type: string return value type: boolean example string empty = ''; string nullstring = null; system.assert(string.isempty(empty)); system.assert(string.isempty(nullstring)); string whitespace = ' '; string alpha = 'hello'; system.assert( |
!string.isempty(whitespace)); system.assert(!string.isempty(alpha)); isnotblank(inputstring) returns true if the specified string is not whitespace, not empty (''), and not null; otherwise, returns false. signature public static boolean isnotblank(string inputstring) 3381apex reference guide string class parameters inputstring type: string return value type: boolean example string alpha = 'hello world!'; system.assert(string.isnotblank(alpha)); string blank = ''; string nullstring = null; string whitespace = ' '; system.assert(!string.isnotblank(blank)); system.assert(!string.isnotblank(nullstring)); system.assert(!string.isnotblank(whitespace)); isnotempty(inputstring) returns true if the specified string is not empty ('') and not null; otherwise, returns false. signature public static boolean isnotempty(string inputstring) parameters inputstring type: string return value type: boolean example string whitespace = ' '; string alpha = 'hello world!'; system.assert(string.isnotempty(whitespace)); system.assert(string.isnotempty(alpha)); string empty = ''; string nullstring = null; system.assert(!string.isnotempty(empty)); system.assert(!string.isnotempty(nullstring)); isnumeric() returns true if the current string contains only unicode digits; otherwise, returns false. 3382 |
apex reference guide string class signature public boolean isnumeric() return value type: boolean usage a decimal point (1.2) is not a unicode digit. example string numeric = '1234567890'; system.assert(numeric.isnumeric()); string alphanumeric = 'r32'; string decimalpoint = '1.2'; system.assert(!alphanumeric.isnumeric()); system.assert(!decimalpoint.isnumeric()); isnumericspace() returns true if the current string contains only unicode digits or spaces; otherwise, returns false. signature public boolean isnumericspace() return value type: boolean usage a decimal point (1.2) is not a unicode digit. example string numericspace = '1 2 3'; system.assert(numericspace.isnumericspace()); string notnumericspace = 'fd3s fc3s'; system.assert(!notnumericspace.isnumericspace()); iswhitespace() returns true if the current string contains only white space characters or is empty; otherwise, returns false. signature public boolean iswhitespace() 3383apex reference guide string class return value type: boolean example string whitespace = ' '; string blank = ''; system.assert(whitespace.iswhitespace()); system.assert(blank.iswhitespace()); string alphanum = 'sil80'; system.assert(!alphanum.iswhitespace()); join(iterableobj, separator) joins the elements of the specified iterable object, such as a list, into a single string separated by the specified separator. signature public static string join(object iterableobj, string separator) parameters iterableobj type: object separator type: string return value type: string usage list<integer> li = new list<integer> {10, 20, 30}; string s = string.join( li, '/'); system.assertequals( '10/20/30', s); lastindexof(substring) returns the index of the last occurrence of the specified substring. if the substring does not occur, this method returns -1. signature public integer lastindexof(string substring) 3384apex reference guide string class parameters substring type: string return value type: integer example string s1 = 'abcdefgc'; integer i1 = s1.lastindexof('c'); system.assertequals(7, i1); lastindexof(substring, endposition) returns the index of the last occurrence of the specified substring, starting from the character at index 0 and ending at the specified index. signature public integer lastindexof(string substring, integer endposition) parameters substring type: string endposition type: integer return value type: integer usage if the substring doesn’t occur or endposition is negative, this method returns -1. if endposition is larger than the last index in the current string, the entire string is searched. example string s1 = 'abcdaacd'; integer i1 = s1.lastindexof('c', 7); system.assertequals(6, i1); integer i2 = s1.lastindexof('c', 3); system.assertequals(2, i2); lastindexofchar(character) returns the index of the last occurrence of the character that corresponds to the specified character value. 3385apex reference guide string class signature public integer lastindexofchar(integer character) parameters character type: integer the integer value of the character in the string. return value type: integer the index of the last occurrence of the specified character, -1 if the character is not found. usage the index that this method returns is in unicode code units. example string str = '\u03a9 is ω (omega)'; // get the last occurrence of omega. system.assertequals(5, str.lastindexofchar(937)); lastindexofchar(character, endindex) returns the index of the last occurrence of the character that corresponds to the specified character value, starting from the specified index. signature public integer lastindexofchar(integer character, integer endindex) parameters character type: integer the integer value of |
the character to look for. endindex type: integer the index to end the search at. return value type: integer the index, starting from the specified start index, of the last occurrence of the specified character. -1 if the character is not found. 3386apex reference guide string class usage the index that this method returns is in unicode code units. example this example shows different ways of searching for the index of the last occurrence of the omega character. the first call to lastindexofchar doesn’t specify an end index and therefore the returned index is 12, which is the last occurrence of omega in the entire string. the subsequent calls specify an end index to find the last occurrence of omega in substrings. string str = 'ω and \u03a9 and ω'; system.assertequals(12, str.lastindexofchar(937)); system.assertequals(6, str.lastindexofchar(937,11)); system.assertequals(0, str.lastindexofchar(937,5)); lastindexofignorecase(substring) returns the index of the last occurrence of the specified substring regardless of case. signature public integer lastindexofignorecase(string substring) parameters substring type: string return value type: integer usage if the substring doesn’t occur, this method returns -1. example string s1 = 'abcdaacd'; integer i1 = s1.lastindexofignorecase('daac'); system.assertequals(3, i1); lastindexofignorecase(substring, endposition) returns the index of the last occurrence of the specified substring regardless of case, starting from the character at index 0 and ending at the specified index. signature public integer lastindexofignorecase(string substring, integer endposition) 3387apex reference guide string class parameters substring type: string endposition type: integer return value type: integer usage if the substring doesn’t occur or endposition is negative, this method returns -1. if endposition is larger than the last index in the current string, the entire string is searched. example string s1 = 'abcdaacd'; integer i1 = s1.lastindexofignorecase('c', 7); system.assertequals(6, i1); left(length) returns the leftmost characters of the current string of the specified length. signature public string left(integer length) parameters length type: integer return value type: string usage if length is greater than the string size, the entire string is returned. example string s1 = 'abcdaacd'; string s2 = s1.left(3); system.assertequals('abc', s2); 3388apex reference guide string class leftpad(length) returns the current string padded with spaces on the left and of the specified length. signature public string leftpad(integer length) parameters length type: integer 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 = s1.leftpad(5); system.assertequals(' abc', s2); leftpad(length, padstr) returns the current string padded with string padstr on the left and of the specified length. signature public string leftpad(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 3389apex reference guide string class example string s1 = 'abc'; string s2 = 'xy'; string s3 = s1.leftpad(7,s2); system.assertequals('xyxyabc', s3); length() returns the number of 16-bit unicode characters contained in the string. signature public integer length() return value type: integer example string mystring = 'abcd'; integer result = mystring.length(); system.assertequals(result, 4); mid(startindex, length) returns a new string that begins with the character at the specified zero-based startindex with |
the number of characters specified by length. signature public string mid(integer startindex, integer length) parameters startindex type: integer if startindex is negative, it is considered to be zero. length type: integer if length is negative or zero, an empty string is returned. if length is greater than the remaining characters, the remainder of the string is returned. return value type: string 3390apex reference guide string class usage this method is similar to the substring(startindex) and substring(startindex, endindex) methods, except that the second argument is the number of characters to return. example string s = 'abcde'; string s2 = s.mid(2, 3); system.assertequals( 'cde', s2); normalizespace() returns the current string with leading, trailing, and repeating white space characters removed. signature public string normalizespace() return value type: string usage this method normalizes the following white space characters: space, tab (\t), new line (\n), carriage return (\r), and form feed (\f). example string s1 = 'salesforce \t force.com'; string s2 = s1.normalizespace(); system.assertequals( 'salesforce force.com', s2); offsetbycodepoints(index, codepointoffset) returns the index of the unicode code point that is offset by the specified number of code points, starting from the given index. signature public integer offsetbycodepoints(integer index, integer codepointoffset) parameters index type: integer the start index in the string. 3391apex reference guide string class codepointoffset type: integer the number of code points to be offset. return value type: integer the index that corresponds to the start index that is added to the offset. usage unpaired surrogates within the text range that is specified by index and codepointoffset count as one code point each. example this example calls offsetbycodepoints on a string with a start index of 0 (to start from the first character) and an offset of three code points. the string contains one sequence of supplementary characters in escaped form (a pair of characters). after an offset of three code points when counting from the beginning of the string, the returned code point index is four. string str = 'a \ud835\udd0a bc'; system.assertequals(4, str.offsetbycodepoints(0,3)); remove(substring) removes all occurrences of the specified substring and returns the string result. signature public string remove(string substring) parameters substring type: string return value type: string example string s1 = 'salesforce and force.com'; string s2 = s1.remove('force'); system.assertequals( 'sales and .com', s2); removeend(substring) removes the specified substring only if it occurs at the end of the string. 3392apex reference guide string class signature public string removeend(string substring) parameters substring type: string return value type: string example string s1 = 'salesforce and force.com'; string s2 = s1.removeend('.com'); system.assertequals( 'salesforce and force', s2); removeendignorecase(substring) removes the specified substring only if it occurs at the end of the string using a case-insensitive match. signature public string removeendignorecase(string substring) parameters substring type: string return value type: string example string s1 = 'salesforce and force.com'; string s2 = s1.removeendignorecase('.com'); system.assertequals('salesforce and force', s2); removestart(substring) removes the specified substring only if it occurs at the beginning of the string. signature public string removestart(string substring) 3393apex reference guide string class parameters substring type: string return value type: string example string s1 = 'salesforce and force.com'; string s2 = s1.removestart('sales'); system.assertequals( 'force and force.com', s2); removestartignorecase(substring) removes the specified substring only if it occurs at |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.