text
stringlengths 24
5.1k
|
---|
sa-sha512, ecdsa-sha256, ecdsa-sha384, and ecdsa-sha512. rsa-sha1 is an rsa signature (with an asymmetric key pair) of an sha1 hash. rsa-sha256 is an rsa signature of an sha256 hash. rsa-sha384 is an rsa signature of an sha384 hash. rsa-sha512 is an rsa signature of an sha512 hash. rsa is the same as rsa-sha1. ecdsa-sha256 is an ecdsa signature of an sha256 hash. ecdsa-sha384 is an ecdsa signature of an sha384 hash. ecdsa-sha512 is an ecdsa signature of an sha512 hash. input type: blob the data to sign. privatekey type: blob the value of privatekey must be decoded using the encodingutilbase64decode method, and should be in rsa's pkcs #8 (1.2) private-key information syntax standard form. the value cannot exceed 4 kb. return value type: blob example the following snippet shows how to call the sign method. string algorithmname = 'rsa'; string key = ''; blob privatekey = encodingutil.base64decode(key); blob input = blob.valueof('12345qwerty'); crypto.sign(algorithmname, input, privatekey); signwithcertificate(algorithmname, input, certdevname) computes a unique digital signature for the input string, using the specified algorithm and the supplied certificate and key pair. signature public static blob signwithcertificate(string algorithmname, blob input, string certdevname) 2839apex reference guide crypto class parameters algorithmname type: string the algorithm name. the valid values for algorithmname are rsa, rsa-sha1, rsa-sha256, rsa-sha384, rsa-sha512,ecdsa-sha256, ecdsa-sha384, and ecdsa-sha512. rsa-sha1 is an rsa signature (with an asymmetric key pair) of an sha1 hash. rsa-sha256 is an rsa signature of an sha256 hash. rsa-sha384 is an rsa signature of an sha384 hash. rsa-sha512 is an rsa signature of an sha512 hash. rsa is the same as rsa-sha1. ecdsa-sha256 is an ecdsa signature of an sha256 hash. ecdsa-sha384 is an ecdsa signature of an sha384 hash. ecdsa-sha512 is an ecdsa signature of an sha512 hash. input type: blob the data to sign. certdevname type: string the unique name for a certificate stored in the salesforce org’s certificate and key management page to use for signing. to access the certificate and key management page from setup, enter certificate and key management in the quick find box, then select certificate and key management. return value type: blob example the following snippet is an example of the method for signing the content referenced by data. blob data = blob.valueof('12345qwerty'); system.crypto.signwithcertificate('rsa-sha512', data, 'signingcert'); signxml(algorithmname, node, idattributename, certdevname) envelops the signature into an xml document. signature public void signxml(string algorithmname, dom.xmlnode node, string idattributename, string certdevname) 2840apex reference guide crypto class parameters algorithmname type: string the rsa encryption algorithm name. valid names are rsa, rsa-sha1, rsa-sha256, rsa-sha384, rsa-sha512,ecdsa-sha256, ecdsa-sha384, and ecdsa-sha512. rsa-sha1 is an rsa signature (with an asymmetric key pair) of an sha1 hash. rsa-sha256 is an rsa signature of an sha256 hash. rsa-sha384 is an rsa signature of an sha384 hash. rsa-sha512 is an rsa signature of an sha512 hash. rsa is the same as rsa-sha1. ecdsa-sha256 is an ecdsa signature of an sha256 hash. ecdsa-sha384 is an ecdsa signature of an sha384 hash. ecdsa-sha512 is an ecdsa signature of |
an sha512 hash. node type: dom.xmlnode the xml node to sign and insert the signature into. idattributename type: string the full name (including the namespace) of the attribute on the node (xmlnode) to use as the reference id. if null, this method uses the id attribute on the node. if there is no id attribute, salesforce generates a new id and adds it to the node. certdevname type: string the unique name for a certificate stored in the salesforce org’s certificate and key management page to use for signing. to access the certificate and key management page from setup, enter certificate and key management in the quick find box, then select certificate and key management. return value type: void example the following is an example declaration and initialization. dom.document doc = new dom.document(); doc.load(...); system.crypto.signxml('rsa-sha512', doc.getrootelement(), null, 'signingcert'); return doc.toxmlstring(); signxml(algorithmname, node, idattributename, certdevname, refchild) inserts the signature envelope before the specified child node. 2841apex reference guide crypto class signature public static void signxml(string algorithmname, dom.xmlnode node, string idattributename, string certdevname, dom.xmlnode refchild) parameters algorithmname type: string the rsa encryption algorithm name. valid names are rsa, rsa-sha1, rsa-sha256, rsa-sha384, rsa-sha512,ecdsa-sha256, ecdsa-sha384, and ecdsa-sha512. rsa-sha1 is an rsa signature (with an asymmetric key pair) of an sha1 hash. rsa-sha256 is an rsa signature of an sha256 hash. rsa-sha384 is an rsa signature of an sha384 hash. rsa-sha512 is an rsa signature of an sha512 hash. rsa is the same as rsa-sha1. ecdsa-sha256 is an ecdsa signature of an sha256 hash. ecdsa-sha384 is an ecdsa signature of an sha384 hash. ecdsa-sha512 is an ecdsa signature of an sha512 hash. node type: dom.xmlnode the xml node to sign and insert the signature into. idattributename type: string the full name (including the namespace) of the attribute on the node (xmlnode) to use as the reference id. if null, this method uses the id attribute on the node. if there is no id attribute, salesforce generates a new id and adds it to the node. certdevname type: string the unique name for a certificate stored in the salesforce org’s certificate and key management page to use for signing. to access the certificate and key management page from setup, enter certificate and key management in the quick find box, then select certificate and key management. refchild dom.xmlnode the xml node before which to insert the signature. if refchild is null, the signature is added at the end. return value type: void verify(string algorithmname, blob data, blob signature, blob publickey) verifies the digital signature for the blob data using the specified algorithm and the supplied public key. use this method to verify a blob signed by a digital signature created using a third-party application or the sign method. 2842apex reference guide crypto class signature public static blob verify(string algorithmname, blob data, blob signature, blob publickey) parameters algorithmname type: string the algorithm name. the valid values for algorithmname are rsa, rsa-sha1, rsa-sha256, rsa-sha384, rsa-sha512,ecdsa-sha256, ecdsa-sha384, and ecdsa-sha512. rsa-sha1 is an rsa signature (with an asymmetric key pair) of an sha1 hash. rsa-sha256 is an rsa signature of an sha256 hash. rsa-sha384 is an rsa signature of an sha384 hash. rsa-sha512 is an rsa signature of an sha512 hash. rsa is the same as rsa-sha1. ecdsa-sha256 is an ecdsa signature of an sha256 hash. ecdsa-sha384 is an ecdsa signature of an sha384 hash. ecdsa-sha512 is an ecdsa signature |
of an sha512 hash. data type: blob the data to sign. signature type: blob the rsa signature. publickey type: blob the value of publickey must be decoded using the encodingutilbase64decode method, and be in x.509 standard. return value type: blob example string algorithmname = 'rsa'; string privatekey = ''; string publickey = ''; blob privatekey = encodingutil.base64decode(privatekey); blob publickey = encodingutil.base64decode(publickey); blob input = blob.valueof('12345qwerty'); blob signature = crypto.sign(algorithmname, input, privatekey); boolean verified = crypto.verify(algorithmname, input, signature, publickey); 2843apex reference guide crypto class verify(string algorithmname, blob data, blob signature, string certdevname) verifies the digital signature for the blob data using the specified algorithm and the public key associated with the certdevname. use this method to verify a blob signed by a digital signature created using a third-party application or the sign method. signature public static blob verify(string algorithmname, blob data, blob signature, string certdevname) parameters algorithmname type: string the algorithm name. the valid values for algorithmname are rsa, rsa-sha1, rsa-sha256, rsa-sha384, rsa-sha512,ecdsa-sha256, ecdsa-sha384, and ecdsa-sha512. rsa-sha1 is an rsa signature (with an asymmetric key pair) of an sha1 hash. rsa-sha256 is an rsa signature of an sha256 hash. rsa-sha384 is an rsa signature of an sha384 hash. rsa-sha512 is an rsa signature of an sha512 hash. rsa is the same as rsa-sha1. ecdsa-sha256 is an ecdsa signature of an sha256 hash. ecdsa-sha384 is an ecdsa signature of an sha384 hash. ecdsa-sha512 is an ecdsa signature of an sha512 hash. data type: blob the data to sign. signature type: blob the rsa signature. certdevname type: string the unique name for a certificate stored in the salesforce organization’s certificate and key management page to use for signing. to access the certificate and key management page from setup, enter certificate and key management in the quick find box, then select certificate and key management. return value type: blob 2844apex reference guide crypto class example blob data = blob.valueof('12345qwerty'); blob signature = crypto.signwithcertificate('rsa-sha256', data, 'signingcert'); boolean verified = crypto.verify('rsa-sha512', data, signature, 'signingcert'); verifyhmac(string algorithmname, blob input, blob privatekey, blob mactoverify) verifies the hmac signature for blob data using the specified algorithm, input data, privatekey, and the mac. use this method to verify a blob signed by a digital signature created using a third-party application or the sign method. signature public static blob verifyhmac(string algorithmname, blob input, blob privatekey, blob mactoverify) parameters algorithmname type: string the valid values for algorithmname are: • hmacmd5 • hmacsha1 • hmacsha256 • hmacsha512 data type: blob the data to sign. privatekey type: blob the value of privatekey does not need to be in decoded form. the value cannot exceed 4 kb. hmactoverify type: blob the value of the mac must be verified against the provided privatekey, data, and algorithm. return value type: boolean example string salt = string.valueof(crypto.getrandominteger()); string key = 'key'; blob mac = crypto.generatemac('hmacsha256', blob.valueof(salt), blob.valueof(key)); boolean verified = crypto.verifyhmac('hmacsha256', blob.valueof(salt), blob.valueof(key), mac); 28 |
45apex reference guide custom metadata type methods custom metadata type methods custom metadata types are customizable, deployable, packageable, and upgradeable application metadata. all custom metadata is exposed in the application cache, which allows access without repeated queries to the database. the metadata is then available for formula fields, validation rules, flows, apex, and soap api. all methods are static. usage custom metadata types methods are instance type methods and are called by and operate on a specific instance of a custom metadata type. custom metadata types example the following example uses the getall() method. the custom metadata type named games has a field called gametype__c. this example determines if the field value of the first record is equal to the string pc. list<games__mdt> mcs = games__mdt.getall().values(); boolean textfield = null; if (mcs[0].gametype__c == 'pc') { textfield = true; } system.assertequals(textfield, true); in this section: getall() returns a map containing custom metadata records for the specific custom metadata type. the map keys are the record developernames and the map values are the record sobjects. getinstance(recordid) returns a single custom metadata type record sobject for a specified record id. getinstance(developername) returns a single custom metadata type record sobject for a specified developername field of the custom metadata type object. getinstance(qualifiedapiname) returns a single custom metadata type record sobject for a qualified api name. getall() returns a map containing custom metadata records for the specific custom metadata type. the map keys are the record developernames and the map values are the record sobjects. signature public map<string, custommetadatatype__mdt> getall() return value type: map<string, custommetadatatype__mdt> 2846apex reference guide custom metadata type methods usage if no records are defined for the type, this method returns an empty map. to iterate over the list of custom metadata type record sobjects, use getall().values(). only the first 255 characters are returned for any field in a custom metadata type record, so longer text fields get truncated. if you want all the field data from a custom metadata type record, use a soql query. example this sample returns a map of all the records for a custom metadata type named games__mdt. map<string, games__mdt> mcs = games__mdt.getall(); getinstance(recordid) returns a single custom metadata type record sobject for a specified record id. signature public custommetadatatype__mdt getinstance(recordid) parameters recordid type: string return value type: custommetadatatype__mdt usage use this method to explicitly retrieve custom metadata type information at the user level. only the first 255 characters of any field in a custom metadata type record are returned. therefore, fields such as long text fields can be truncated. if you want all the field data from a custom metadata type record, use a soql query. example this sample returns a single record sobject for the custom metadata type named games_mdt with recordid specified as m00000000000001. games__mdt mc = games__mdt.getinstance('m00000000000001'); getinstance(developername) returns a single custom metadata type record sobject for a specified developername field of the custom metadata type object. signature public custommetadatatype__mdt getinstance(string developername) 2847apex reference guide custom metadata type methods parameters developername type: string return value type: custommetadatatype__mdt usage use this method to return a single custom metadata type record for the specified developername. the developername is the unique name of the custom metadata type object in the api. only the first 255 characters of any field in a custom metadata type record are returned. therefore, fields such as long text fields can be truncated. if you want all the field data from a custom metadata type record, use a soql query. example returns a single record sobject for the custom metadata type named games_mdt with developername specified as firstrecord. games__mdt mc = games__mdt.getinstance('firstrecord'); getinstance(qualifiedapiname) returns a single custom metadata type record sobject for a qualified api name. signature public custommetadatatype__mdt getinstance(string qualifiedapiname |
) parameters qualifiedapiname type: string return value type: custommetadatatype__mdt usage use this method to return a single custom metadata type record for the specified qualifiedapiname. the qualifiedapiname is a concatenation of the namespace prefix and developername, and has this format: namespaceprefix__developername. the developername is the unique name of the custom metadata type object in the api. only the first 255 characters of any field in a custom metadata type record are returned. therefore, fields such as long text fields can be truncated. if you want all the field data from a custom metadata type record, use a soql query. 2848apex reference guide custom settings methods example this sample returns a single record sobject for the custom metadata type named games_mdt with qualified api name specified as mynamespace__firstrecord. games__mdt mc = games__mdt.getinstance('mynamespace__firstrecord'); custom settings methods custom settings are similar to custom objects and enable application developers to create custom sets of data, as well as create and associate custom data for an organization, profile, or specific user. all custom settings data is exposed in the application cache, which enables efficient access without the cost of repeated queries to the database. this data is then available for formula fields, validation rules, flows, apex, and the soap api. usage custom settings methods are all instance methods, that is, they are called by and operate on a specific instance of a custom setting. there are two types of custom settings: hierarchy and list. there are two types of methods: methods that work with list custom settings, and methods that work with hierarchy custom settings. note: all custom settings data is exposed in the application cache, which enables efficient access without the cost of repeated queries to the database. however, querying custom settings data using standard object query language (soql) doesn't use the application cache and is similar to querying a custom object. to benefit from caching, use other methods for accessing custom settings data such as the apex custom settings methods. for more information on creating custom settings in the salesforce user interface, see “create custom settings” in the salesforce online help. custom setting examples the following example uses a list custom setting called games. the games setting has a field called gametype. this example determines if the value of the first data set is equal to the string pc. list<games__c> mcs = games__c.getall().values(); boolean textfield = null; if (mcs[0].gametype__c == 'pc') { textfield = true; } system.assertequals(textfield, true); the following example uses a custom setting called foundation_countries. this example demonstrates that the getvalues and getinstance methods return identical values. foundation_countries__c mycs1 = foundation_countries__c.getvalues('united states'); string myccval = mycs1.country_code__c; foundation_countries__c mycs2 = foundation_countries__c.getinstance('united states'); string myccinst = mycs2.country_code__c; system.assertequals(myccinst, myccval); 2849apex reference guide custom settings methods hierarchy custom setting examples in the following example, the hierarchy custom setting gamessupport has a field called corporate_number. the code returns the value for the profile specified with pid. gamessupport__c mhc = gamessupport__c.getinstance(pid); string mphone = mhc.corporate_number__c; the example is identical if you choose to use the getvalues method. the following example shows how to use hierarchy custom settings methods. for getinstance, the example shows how field values that aren't set for a specific user or profile are returned from fields defined at the next lowest level in the hierarchy. the example also shows how to use getorgdefaults. finally, the example demonstrates how getvalues returns fields in the custom setting record only for the specific user or profile, and doesn't merge values from other levels of the hierarchy. instead, getvalues returns null for any fields that aren't set. this example uses a hierarchy custom setting called hierarchy. hierarchy has two fields: overrideme and dontoverrideme. in addition, a user named robert has a system administrator profile. the organization, profile, and user settings for this example are as follows: organization settings overrideme: hello dontoverrideme: world profile settings overrideme |
: goodbye dontoverrideme is not set. user settings overrideme: fluffy dontoverrideme is not set. the following example demonstrates the result of the getinstance method when robert calls it in his organization: hierarchy__c cs = hierarchy__c.getinstance(); system.assert(cs.overrideme__c == 'fluffy'); system.assert(cs.dontoverrideme__c == 'world'); if robert passes his user id specified by robertid to getinstance, the results are the same. the identical results are because the lowest level of data in the custom setting is specified at the user level. hierarchy__c cs = hierarchy__c.getinstance(robertid); system.assert(cs.overrideme__c == 'fluffy'); system.assert(cs.dontoverrideme__c == 'world'); if robert passes the system administrator profile id specified by sysadminid to getinstance, the result is different. the data specified for the profile is returned: hierarchy__c cs = hierarchy__c.getinstance(sysadminid); system.assert(cs.overrideme__c == 'goodbye'); system.assert(cs.dontoverrideme__c == 'world'); when robert tries to return the data set for the organization using getorgdefaults, the result is: hierarchy__c cs = hierarchy__c.getorgdefaults(); system.assert(cs.overrideme__c == 'hello'); system.assert(cs.dontoverrideme__c == 'world'); 2850apex reference guide custom settings methods by using the getvalues method, robert can get the hierarchy custom setting values specific to his user and profile settings. for example, if robert passes his user id robertid to getvalues, the result is: hierarchy__c cs = hierarchy__c.getvalues(robertid); system.assert(cs.overrideme__c == 'fluffy'); // note how this value is null, because you are returning // data specific for the user system.assert(cs.dontoverrideme__c == null); if robert passes his system administrator profile id sysadminid to getvalues, the result is: hierarchy__c cs = hierarchy__c.getvalues(sysadminid); system.assert(cs.overrideme__c == 'goodbye'); // note how this value is null, because you are returning // data specific for the profile system.assert(cs.dontoverrideme__c == null); country and state code custom settings example this example illustrates using two custom setting objects for storing related information, and a visualforce page to display the data in a set of related picklists. in the following example, country and state codes are stored in two different custom settings: foundation_countries and foundation_states. the foundation_countries custom setting is a list type custom setting and has a single field, country_code. the foundation_states custom setting is also a list type of custom setting and has the following fields: • country code • state code • state name 2851apex reference guide custom settings methods the visualforce page shows two picklists: one for country and one for state. <apex:page controller="countrystatepicker"> <apex:form > <apex:actionfunction name="rerenderstates" rerender="statesselectlist" > <apex:param name="firstparam" assignto="{!country}" value="" /> </apex:actionfunction> <table><tbody> <tr> <th>country</th> <td> <apex:selectlist id="country" styleclass="std" size="1" value="{!country}" onchange="rerenderstates(this.value)"> <apex:selectoptions value="{!countriesselectlist}"/> </apex:selectlist> </td> </tr> <tr id="state_input"> 2852apex reference guide custom settings methods <th>state/province</th> <td> <apex:selectlist id="statesselectlist" styleclass="std" size="1" value="{!state}"> <apex:selectoptions value="{!statesselectlist}"/> </apex:selectlist> </td> </tr> </tbody></table> </apex:form> </apex:page> the apex controller countrystatepicker finds the values |
entered into the custom settings, then returns them to the visualforce page. public with sharing class countrystatepicker { // variables to store country and state selected by user public string state { get; set; } public string country {get; set;} // generates country dropdown from country settings public list<selectoption> getcountriesselectlist() { list<selectoption> options = new list<selectoption>(); options.add(new selectoption('', '-- select one --')); // find all the countries in the custom setting map<string, foundation_countries__c> countries = foundation_countries__c.getall(); // sort them by name list<string> countrynames = new list<string>(); countrynames.addall(countries.keyset()); countrynames.sort(); // create the select options. for (string countryname : countrynames) { foundation_countries__c country = countries.get(countryname); options.add(new selectoption(country.country_code__c, country.name)); } return options; } // to generate the states picklist based on the country selected by user. public list<selectoption> getstatesselectlist() { list<selectoption> options = new list<selectoption>(); // find all the states we have in custom settings. map<string, foundation_states__c> allstates = foundation_states__c.getall(); // filter states that belong to the selected country map<string, foundation_states__c> states = new map<string, foundation_states__c>(); for(foundation_states__c state : allstates.values()) { if (state.country_code__c == this.country) { states.put(state.name, state); 2853apex reference guide custom settings methods } } // sort the states based on their names list<string> statenames = new list<string>(); statenames.addall(states.keyset()); statenames.sort(); // generate the select options based on the final sorted list for (string statename : statenames) { foundation_states__c state = states.get(statename); options.add(new selectoption(state.state_code__c, state.state_name__c)); } // if no states are found, just say not required in the dropdown. if (options.size() > 0) { options.add(0, new selectoption('', '-- select one --')); } else { options.add(new selectoption('', 'not required')); } return options; } } in this section: list custom setting methods hierarchy custom setting methods see also: apex developer guide: custom settings list custom setting methods the following are instance methods for list custom settings. in this section: getall() returns a map of the data sets defined for the custom setting. getinstance(datasetname) returns the custom setting data set record for the specified data set name. this method returns the exact same object as getvalues(datasetname). getvalues(datasetname) returns the custom setting data set record for the specified data set name. this method returns the exact same object as getinstance(datasetname). 2854apex reference guide custom settings methods getall() returns a map of the data sets defined for the custom setting. signature public map<string, customsetting__c> getall() return value type: map<string, customsetting__c> usage if no data set is defined, this method returns an empty map. note: for apex saved using salesforce api version 20.0 or earlier, the data set names, which are the keys in the returned map, are converted to lower case. for apex saved using salesforce api version 21.0 and later, the case of the data set names in the returned map keys is not changed and the original case is preserved. getinstance(datasetname) returns the custom setting data set record for the specified data set name. this method returns the exact same object as getvalues(datasetname). signature public customsetting__c getinstance(string datasetname) parameters datasetname type: string return value type: customsetting__c usage if no data is defined for the specified data set, this method returns null. getvalues(datasetname) returns the custom setting data set record for the specified data set name. |
this method returns the exact same object as getinstance(datasetname). signature public customsetting__c getvalues(string datasetname) 2855apex reference guide custom settings methods parameters datasetname type: string return value type: customsetting__c usage if no data is defined for the specified data set, this method returns null. hierarchy custom setting methods the following are instance methods for hierarchy custom settings. note: • in api version 41.0 and below, each method in an apex test class, including testsetup methods, are able to insert hierarchy custom setting values. this behavior is true even when the methods have the same setupownerid value as a hierarchy custom setting record inserted in a different test method. • in api version 42.0 and later, if a hierarchy custom setting is inserted in a testsetup method, inserting a hierarchy custom setting record with the same setupownerid in a test method throws a duplicate_value exception. in this section: getinstance() returns a custom setting data set record for the current user. the fields returned in the custom setting record are merged based on the lowest level fields that are defined in the hierarchy. getinstance(userid) returns the custom setting data set record for the specified user id. the lowest level custom setting record and fields are returned. use this when you want to explicitly retrieve data for the custom setting at the user level. getinstance(profileid) returns the custom setting data set record for the specified profile id. the lowest level custom setting record and fields are returned. use this when you want to explicitly retrieve data for the custom setting at the profile level. getorgdefaults() returns the custom setting data set record for the organization. getvalues(userid) returns the custom setting data set record for the specified user id. getvalues(profileid) returns the custom setting data set for the specified profile id. getinstance() returns a custom setting data set record for the current user. the fields returned in the custom setting record are merged based on the lowest level fields that are defined in the hierarchy. 2856apex reference guide custom settings methods signature public customsetting__c getinstance() return value type: customsetting__c usage if no custom setting data is defined for the user, this method returns a new custom setting object. the new custom setting object contains an id set to null and merged fields from higher in the hierarchy. you can add this new custom setting record for the user by using insert or upsert. if no custom setting data is defined in the hierarchy, the returned custom setting has empty fields, except for the setupownerid field which contains the user id. note: for apex saved using salesforce api version 21.0 or earlier, this method returns the custom setting data set record with fields merged from field values defined at the lowest hierarchy level, starting with the user. also, if no custom setting data is defined in the hierarchy, this method returns null. this method is equivalent to a method call to getinstance(user_id) for the current user. example • custom setting data set defined for the user: if you have a custom setting data set defined for the user “uriel jones,” for the profile “system administrator,” and for the organization as a whole, and the user running the code is uriel jones, this method returns the custom setting record defined for uriel jones. • merged fields: if you have a custom setting data set with fields a and b for the user “uriel jones” and for the profile “system administrator,” and field a is defined for uriel jones, field b is null but is defined for the system adminitrator profile, this method returns the custom setting record for uriel jones with field a for uriel jones and field b from the system administrator profile. • no custom setting data set record defined for the user: if the current user is “barbara mahonie,” who also shares the “system administrator” profile, but no data is defined for barbara as a user, this method returns a new custom setting record with the id set to null and with fields merged based on the fields defined in the lowest level in the hierarchy. getinstance(userid) returns the custom setting data set record for the specified user id. the lowest level custom setting record and fields are returned. use this when you want to explicitly retrieve data for the custom setting at the user level. signature public customsetting__c getinstance(id userid) parameters userid type: id return value type: customsetting__c 2857a |
pex reference guide custom settings methods usage if no custom setting data is defined for the user, this method returns a new custom setting object. the new custom setting object contains an id set to null and merged fields from higher in the hierarchy. you can add this new custom setting record for the user by using insert or upsert. if no custom setting data is defined in the hierarchy, the returned custom setting has empty fields, except for the setupownerid field which contains the user id. note: for apex saved using salesforce api version 21.0 or earlier, this method returns the custom setting data set record with fields merged from field values defined at the lowest hierarchy level, starting with the user. also, if no custom setting data is defined in the hierarchy, this method returns null. getinstance(profileid) returns the custom setting data set record for the specified profile id. the lowest level custom setting record and fields are returned. use this when you want to explicitly retrieve data for the custom setting at the profile level. signature public customsetting__c getinstance(id profileid) parameters profileid type: id return value type: customsetting__c usage if no custom setting data is defined for the profile, this method returns a new custom setting record. the new custom setting object contains an id set to null and with merged fields from your organization's default values. you can add this new custom setting for the profile by using insert or upsert. if no custom setting data is defined in the hierarchy, the returned custom setting has empty fields, except for the setupownerid field which contains the profile id. note: for apex saved using salesforceapi version 21.0 or earlier, this method returns the custom setting data set record with fields merged from field values defined at the lowest hierarchy level, starting with the profile. also, if no custom setting data is defined in the hierarchy, this method returns null. getorgdefaults() returns the custom setting data set record for the organization. signature public customsetting__c getorgdefaults() return value type: customsetting__c 2858apex reference guide custom settings methods usage if no custom setting data is defined for the organization, this method returns an empty custom setting object. note: for apex saved using salesforce api version 21.0 or earlier, this method returns null if no custom setting data is defined for the organization. getvalues(userid) returns the custom setting data set record for the specified user id. signature public customsetting__c getvalues(id userid) parameters userid type: id return value type: customsetting__c usage use this if you only want the subset of custom setting data that has been defined at the user level. for example, suppose you have a custom setting field that has been assigned a value of "alpha" at the organizational level, but has no value assigned at the user or profile level. using getvalues(userid) returns null for this custom setting field. getvalues(profileid) returns the custom setting data set for the specified profile id. signature public customsetting__c getvalues(id profileid) parameters profileid type: id return value type: customsetting__c usage use this if you only want the subset of custom setting data that has been defined at the profile level. for example, suppose you have a custom setting field that has been assigned a value of "alpha" at the organizational level, but has no value assigned at the user or profile level. using getvalues(profileid) returns null for this custom setting field. 2859apex reference guide database class database class contains methods for creating and manipulating data. namespace system usage some database methods also exist as dml statements. see also: apex dml operations database methods the following are methods for database. all methods are static. in this section: convertlead(leadtoconvert, allornone) converts a lead into an account and contact, as well as (optionally) an opportunity. convertlead(leadstoconvert, allornone) converts a list of leadconvert objects into accounts and contacts, as well as (optionally) opportunities. convertlead(leadtoconvert, dmloptions) converts a lead into an account and contact, as well as (optionally) an opportunity. convertlead(leadstoconvert, dmloptions) converts a list of leadconvert objects into accounts and contacts, as well as (optionally) opportunities. convertlead(leadtoconvert, allor |
none, accesslevel) converts a lead into an account and contact, as well as (optionally) an opportunity. convertlead(leadstoconvert, allornone, accesslevel) converts a list of leadconvert objects into accounts and contacts, as well as (optionally) opportunities. convertlead(leadtoconvert, dmloptions, accesslevel) converts a lead into an account and contact, as well as (optionally) an opportunity. convertlead(leadstoconvert, dmloptions, accesslevel) converts a list of leadconvert objects into accounts and contacts, as well as (optionally) opportunities. countquery(query) returns the number of records that a dynamic soql query would return when executed. countquery(query, accesslevel) returns the number of records that a dynamic soql query would return when executed. countquerywithbinds(query, bindmap, accesslevel) returns the number of records that a dynamic soql query would return when executed. bind variables in the query are resolved from the bindmap map parameter directly with the key, rather than from apex code variables. 2860apex reference guide database class delete(recordtodelete, allornone) deletes an existing sobject record, such as an individual account or contact, from your organization's data. delete(recordstodelete, allornone) deletes a list of existing sobject records, such as individual accounts or contacts, from your organization’s data. delete(recordid, allornone) deletes existing sobject records, such as individual accounts or contacts, from your organization’s data. delete(recordids, allornone) deletes a list of existing sobject records, such as individual accounts or contacts, from your organization’s data. delete(recordtodelete, allornone, accesslevel) deletes an existing sobject record, such as an individual account or contact, from your organization's data. delete(recordstodelete, allornone, accesslevel) deletes a list of existing sobject records, such as individual accounts or contacts, from your organization’s data. delete(recordid, allornone, accesslevel) deletes existing sobject records, such as individual accounts or contacts, from your organization’s data. delete(recordids, allornone, accesslevel) deletes a list of existing sobject records, such as individual accounts or contacts, from your organization’s data. deleteasync(sobjects, callback) initiates requests to delete the external data that corresponds to the specified external object records. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. allows referencing a callback class whose processdelete method is called for each record after deletion. deleteasync(sobject, callback) initiates a request to delete the external data that corresponds to the specified external object record. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. allows referencing a callback class whose processdelete method is called after deletion. deleteasync(sobjects) initiates requests to delete the external data that corresponds to the specified external object records. the requests are executed asynchronously, as background operations, and are sent to the external systems that are defined by the external objects' associated external data sources. deleteasync(sobject) initiates a request to delete the external data that corresponds to the specified external object record. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. deleteasync(sobjects, callback, accesslevel) initiates requests to delete the external data that corresponds to the specified external object records. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. allows referencing a callback class whose processdelete method is called for each record after deletion. deleteasync(sobject, callback, accesslevel) initiates a request to delete the external data that corresponds to the specified external object record. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. allows referencing a callback class whose processdelete method is called after deletion. 2861apex reference guide database class deleteasync( |
sobjects, accesslevel) initiates requests to delete the external data that corresponds to the specified external object records. the requests are executed asynchronously, as background operations, and are sent to the external systems that are defined by the external objects' associated external data sources. deleteasync(sobject, accesslevel) initiates a request to delete the external data that corresponds to the specified external object record. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. deleteimmediate(sobjects) initiates requests to delete the external data that corresponds to the specified external object records. the requests are executed synchronously and are sent to the external systems that are defined by the external objects' associated external data sources. if the apex transaction contains pending changes, the synchronous operations can't be completed and throw exceptions. deleteimmediate(sobject) initiates a request to delete the external data that corresponds to the specified external object record. the request is executed synchronously and is sent to the external system that's defined by the external object's associated external data source. if the apex transaction contains pending changes, the synchronous operation can't be completed and throws an exception. deleteimmediate(sobjects, accesslevel) initiates requests to delete the external data that corresponds to the specified external object records. the requests are executed synchronously and are sent to the external systems that are defined by the external objects' associated external data sources. if the apex transaction contains pending changes, the synchronous operations can't be completed and throw exceptions. deleteimmediate(sobject, accesslevel) initiates a request to delete the external data that corresponds to the specified external object record. the request is executed synchronously and is sent to the external system that's defined by the external object's associated external data source. if the apex transaction contains pending changes, the synchronous operation can't be completed and throws an exception. emptyrecyclebin(recordids) permanently deletes the specified records from the recycle bin. emptyrecyclebin(obj) permanently deletes the specified sobject from the recycle bin. emptyrecyclebin(listofsobjects) permanently deletes the specified sobjects from the recycle bin. executebatch(batchclassobject) submits a batch apex job for execution corresponding to the specified class. executebatch(batchclassobject, scope) submits a batch apex job for execution using the specified class and scope. getasyncdeleteresult(deleteresult) retrieves the status of an asynchronous delete operation that’s identified by a database.deleteresult object. getasyncdeleteresult(asynclocator) retrieves the result of an asynchronous delete operation based on the result’s unique identifier. getasynclocator(result) returns the asynclocator associated with the result of a specified asynchronous insert, update, or delete operation. getasyncsaveresult(saveresult) returns the status of an asynchronous insert or update operation that’s identified by a database.saveresult object. 2862apex reference guide database class getasyncsaveresult(asynclocator) returns the status of an asynchronous insert or update operation based on the unique identifier associated with each modification. getdeleted(sobjecttype, startdate, enddate) returns the list of individual records that have been deleted for an sobject type within the specified start and end dates and times and that are still in the recycle bin. getquerylocator(listofqueries) creates a querylocator object used in batch apex or visualforce. getquerylocator(query) creates a querylocator object used in batch apex or visualforce. getquerylocator(listofqueries, accesslevel) creates a querylocator object used in batch apex or visualforce. getquerylocator(query, accesslevel) creates a querylocator object used in batch apex or visualforce. getquerylocatorwithbinds(query, bindmap, accesslevel) creates a querylocator object used in batch apex or visualforce. bind variables in the query are resolved from the bindmap map parameter directly with the key, rather than from apex code variables. getupdated(sobjecttype, startdate, enddate) returns the list of individual records that have been updated for an sobject type within the specified start and end dates and times. insert(recordtoinsert, allornone) |
adds an sobject, such as an individual account or contact, to your organization's data. insert(recordstoinsert, allornone) adds one or more sobjects, such as individual accounts or contacts, to your organization’s data. insert(recordtoinsert, dmloptions) adds an sobject, such as an individual account or contact, to your organization's data. insert(recordstoinsert, dmloptions) adds one or more sobjects, such as individual accounts or contacts, to your organization's data. insert(recordtoinsert, allornone, accesslevel) adds an sobject, such as an individual account or contact, to your organization's data. insert(recordstoinsert, allornone, accesslevel) adds one or more sobjects, such as individual accounts or contacts, to your organization’s data. insert(recordtoinsert, dmloptions, accesslevel) adds an sobject, such as an individual account or contact, to your organization's data. insert(recordstoinsert, dmloptions, accesslevel) adds one or more sobjects, such as individual accounts or contacts, to your organization's data. insertasync(sobjects, callback) initiates requests to add external object data to the relevant external systems. the requests are executed asynchronously, as background operations, and are sent to the external systems that are defined by the external objects' associated external data sources. allows referencing a callback class whose processsave method is called for each record after the remote operations are completed. 2863apex reference guide database class insertasync(sobject, callback) initiates a request to add external object data to the relevant external system. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. allows referencing a callback class whose processsave method is called after the remote operation is completed. insertasync(sobjects) initiates requests to add external object data to the relevant external systems. the requests are executed asynchronously, as background operations, and are sent to the external systems that are defined by the external objects' associated external data sources. insertasync(sobject) initiates a request to add external object data to the relevant external system. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. insertasync(sobjects, callback, accesslevel) initiates requests to add external object data to the relevant external systems. the requests are executed asynchronously, as background operations, and are sent to the external systems that are defined by the external objects' associated external data sources. allows referencing a callback class whose processsave method is called for each record after the remote operations are completed. insertasync(sobject, callback, accesslevel) initiates a request to add external object data to the relevant external system. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. allows referencing a callback class whose processsave method is called after the remote operation is completed. insertasync(sobjects, accesslevel) initiates requests to add external object data to the relevant external systems. the requests are executed asynchronously, as background operations, and are sent to the external systems that are defined by the external objects' associated external data sources. insertasync(sobject, accesslevel) initiates a request to add external object data to the relevant external system. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. insertimmediate(sobjects) initiates requests to add external object data to the relevant external systems. the requests are executed synchronously and are sent to the external systems that are defined by the external objects' associated external data sources. if the apex transaction contains pending changes, the synchronous operations can't be completed and throw exceptions. insertimmediate(sobject) initiates a request to add external object data to the relevant external system. the request is executed synchronously and is sent to the external system that's defined by the external object's associated external data source. if the apex transaction contains pending changes, the synchronous operation can't be completed and throws an exception. insertimmediate(sobjects, accesslevel) initiates requests to add external object data |
to the relevant external systems. the requests are executed synchronously and are sent to the external systems that are defined by the external objects' associated external data sources. if the apex transaction contains pending changes, the synchronous operations can't be completed and throw exceptions. insertimmediate(sobject, accesslevel) initiates a request to add external object data to the relevant external system. the request is executed synchronously and is sent to the external system that's defined by the external object's associated external data source. if the apex transaction contains pending changes, the synchronous operation can't be completed and throws an exception. merge(masterrecord, duplicateid) merges the specified duplicate record into the master sobject record of the same type, deleting the duplicate, and reparenting any related records. merges only accounts, contacts, or leads. 2864apex reference guide database class merge(masterrecord, duplicaterecord) merges the specified duplicate sobject record into the master sobject of the same type, deleting the duplicate, and reparenting any related records. merge(masterrecord, duplicateids) merges up to two records of the same sobject type into the master sobject record, deleting the others, and reparenting any related records. merge(masterrecord, duplicaterecords) merges up to two records of the same object type into the master sobject record, deleting the others, and reparenting any related records. merge(masterrecord, duplicateid, allornone) merges the specified duplicate record into the master sobject record of the same type, optionally returning errors, if any, deleting the duplicate, and reparenting any related records. merges only accounts, contacts, or leads. merge(masterrecord, duplicaterecord, allornone) merges the specified duplicate sobject record into the master sobject of the same type, optionally returning errors, if any, deleting the duplicate, and reparenting any related records. merge(masterrecord, duplicateids, allornone) merges up to two records of the same sobject type into the master sobject record, optionally returning errors, if any, deleting the duplicates, and reparenting any related records. merge(masterrecord, duplicaterecords, allornone) merges up to two records of the same object type into the master sobject record, optionally returning errors, if any, deleting the duplicates, and reparenting any related records. merge(masterrecord, duplicateid, accesslevel) merges the specified duplicate record into the master sobject record of the same type, deleting the duplicate, and reparenting any related records. merges only accounts, contacts, or leads. merge(masterrecord, duplicaterecord, accesslevel) merges the specified duplicate sobject record into the master sobject of the same type, deleting the duplicate, and reparenting any related records. merge(masterrecord, duplicateids, accesslevel) merges up to two records of the same sobject type into the master sobject record, deleting the others, and reparenting any related records. merge(masterrecord, duplicaterecords, accesslevel) merges up to two records of the same object type into the master sobject record, deleting the others, and reparenting any related records. merge(masterrecord, duplicateid, allornone, accesslevel) merges the specified duplicate record into the master sobject record of the same type, optionally returning errors, if any, deleting the duplicate, and reparenting any related records. merges only accounts, contacts, or leads. merge(masterrecord, duplicaterecord, allornone, accesslevel) merges the specified duplicate sobject record into the master sobject of the same type, optionally returning errors, if any, deleting the duplicate, and reparenting any related records. merge(masterrecord, duplicateids, allornone, accesslevel) merges up to two records of the same sobject type into the master sobject record, optionally returning errors, if any, deleting the duplicates, and reparenting any related records. 2865apex reference guide database class merge(masterrecord, duplicaterecords, allornone, accesslevel) merges up to two records of the same object type into the master sobject record, optionally returning errors, if any, deleting the duplicates, and reparenting any related records. query(querystring) creates a dynamic soql query at runtime. query(querystring, accesslevel) creates |
a dynamic soql query at runtime. querywithbinds(querystring, bindmap, accesslevel) creates a dynamic soql query at runtime. bind variables in the query are resolved from the bindmap map parameter directly with the key, rather than from apex code variables. rollback(databasesavepoint) restores the database to the state specified by the savepoint variable. any emails submitted since the last savepoint are also rolled back and not sent. setsavepoint() returns a savepoint variable that can be stored as a local variable, then used with the rollback method to restore the database to that point. undelete(recordtoundelete, allornone) restores an existing sobject record, such as an individual account or contact, from your organization's recycle bin. undelete(recordstoundelete, allornone) restores one or more existing sobject records, such as individual accounts or contacts, from your organization’s recycle bin. undelete(recordid, allornone) restores an existing sobject record, such as an individual account or contact, from your organization's recycle bin. undelete(recordids, allornone) restores one or more existing sobject records, such as individual accounts or contacts, from your organization’s recycle bin. undelete(recordtoundelete, allornone, accesslevel) restores an existing sobject record, such as an individual account or contact, from your organization's recycle bin. undelete(recordstoundelete, allornone, accesslevel) restores one or more existing sobject records, such as individual accounts or contacts, from your organization’s recycle bin. undelete(recordid, allornone, accesslevel) restores an existing sobject record, such as an individual account or contact, from your organization's recycle bin. undelete(recordids, allornone, accesslevel) restores one or more existing sobject records, such as individual accounts or contacts, from your organization’s recycle bin. update(recordtoupdate, allornone) modifies an existing sobject record, such as an individual account or contact, in your organization's data. update(recordstoupdate, allornone) modifies one or more existing sobject records, such as individual accounts or contacts, in your organization’s data. update(recordtoupdate, dmloptions) modifies an existing sobject record, such as an individual account or contact, in your organization's data. update(recordstoupdate, dmloptions) modifies one or more existing sobject records, such as individual accounts or contacts, in your organization’s data. 2866apex reference guide database class update(recordtoupdate, allornone, accesslevel) modifies an existing sobject record, such as an individual account or contact, in your organization's data. update(recordstoupdate, allornone, accesslevel) modifies one or more existing sobject records, such as individual accounts or contacts, in your organization’s data. update(recordtoupdate, dmloptions, accesslevel) modifies an existing sobject record, such as an individual account or contact, in your organization's data. update(recordstoupdate, dmloptions, accesslevel) modifies one or more existing sobject records, such as individual accounts or contacts, in your organization’s data. upsert(recordtoupsert, externalidfield, allornone) creates a new sobject record or updates an existing sobject record within a single statement, using a specified field to determine the presence of existing objects, or the id field if no field is specified. upsert(recordstoupsert, externalidfield, allornone) creates new sobject records or updates existing sobject records within a single statement, using a specified field to determine the presence of existing objects, or the id field if no field is specified. upsert(recordtoupsert, externalidfield, allornone, accesslevel) creates a new sobject record or updates an existing sobject record within a single statement, using a specified field to determine the presence of existing objects, or the id field if no field is specified. upsert(recordstoupsert, externalidfield, allornone, accesslevel) creates new sobject records or updates existing sobject records within a single statement, using a specified field to determine the presence of existing objects, or the id field if |
no field is specified. updateasync(sobjects, callback) initiates requests to update external object data on the relevant external systems. the requests are executed asynchronously, as background operations, and are sent to the external systems that are defined by the external objects' associated external data sources. allows referencing a callback class whose processsave method is called for each record after the remote operations are completed. updateasync(sobject, callback) initiates a request to update external object data on the relevant external system. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. allows referencing a callback class whose processsave method is called after the remote operation is completed. updateasync(sobjects) initiates requests to update external object data on the relevant external systems. the requests are executed asynchronously, as background operations, and are sent to the external systems that are defined by the external objects' associated external data sources. updateasync(sobject) initiates a request to update external object data on the relevant external system. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. updateasync(sobjects, callback, accesslevel) initiates requests to update external object data on the relevant external systems. the requests are executed asynchronously, as background operations, and are sent to the external systems that are defined by the external objects' associated external data sources. allows referencing a callback class whose processsave method is called for each record after the remote operations are completed. 2867apex reference guide database class updateasync(sobject, callback, accesslevel) initiates a request to update external object data on the relevant external system. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. allows referencing a callback class whose processsave method is called after the remote operation is completed. updateasync(sobjects, accesslevel) initiates requests to update external object data on the relevant external systems. the requests are executed asynchronously, as background operations, and are sent to the external systems that are defined by the external objects' associated external data sources. updateasync(sobject, accesslevel) initiates a request to update external object data on the relevant external system. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. updateimmediate(sobjects) initiates requests to update external object data on the relevant external systems. the requests are executed synchronously and are sent to the external systems that are defined by the external objects' associated external data sources. if the apex transaction contains pending changes, the synchronous operations can't be completed and throw exceptions. updateimmediate(sobject) initiates a request to update external object data on the relevant external system. the request is executed synchronously and is sent to the external system that's defined by the external object's associated external data source. if the apex transaction contains pending changes, the synchronous operation can't be completed and throws an exception. updateimmediate(sobjects, accesslevel) initiates requests to update external object data on the relevant external systems. the requests are executed synchronously and are sent to the external systems that are defined by the external objects' associated external data sources. if the apex transaction contains pending changes, the synchronous operations can't be completed and throw exceptions. updateimmediate(sobject, accesslevel) initiates a request to update external object data on the relevant external system. the request is executed synchronously and is sent to the external system that's defined by the external object's associated external data source. if the apex transaction contains pending changes, the synchronous operation can't be completed and throws an exception. convertlead(leadtoconvert, allornone) converts a lead into an account and contact, as well as (optionally) an opportunity. signature public static database.leadconvertresult convertlead(database.leadconvert leadtoconvert, boolean allornone) parameters leadtoconvert type: database.leadconvert allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. 2868apex reference guide database class return value type: database.leadconvertresult usage the convertlead method accepts up to 100 leadconvert objects. each executed convertlead method counts against the governor limit for dml statements. convertlead(leadstoconvert, allornone) converts a list of leadconvert objects into accounts and contacts, as well as (optionally) opportunities. signature public static database.leadconvertresult[] convertlead(database.leadconvert[] leadstoconvert, boolean allornone) parameters leadstoconvert type: database.leadconvert[] allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. return value type: database.leadconvertresult[] usage the convertlead method accepts up to 100 leadconvert objects. each executed convertlead method counts against the governor limit for dml statements. convertlead(leadtoconvert, dmloptions) converts a lead into an account and contact, as well as (optionally) an opportunity. signature public static database.leadconvertresult convertlead(database.leadconvert leadtoconvert, database.dmloptions dmloptions) 2869apex reference guide database class parameters leadtoconvert type: database.leadconvert dmloptions type: database.dmloptions the optional dmloptions parameter specifies additional data for the transaction, such as assignment rule information or rollback behavior when errors occur during record insertions. return value type: database.leadconvertresult usage the convertlead method accepts up to 100 leadconvert objects. each executed convertlead method counts against the governor limit for dml statements. convertlead(leadstoconvert, dmloptions) converts a list of leadconvert objects into accounts and contacts, as well as (optionally) opportunities. signature public static list<database.leadconvertresult> convertlead(list<database.leadconvert> leadstoconvert, database.dmloptions dmloptions) parameters leadstoconvert type: list<database.leadconvert> dmloptions type: database.dmloptions the optional dmloptions parameter specifies additional data for the transaction, such as assignment rule information or rollback behavior when errors occur during record insertions. return value type: list<database.leadconvertresult> usage the convertlead method accepts up to 100 leadconvert objects. each executed convertlead method counts against the governor limit for dml statements. convertlead(leadtoconvert, allornone, accesslevel) converts a lead into an account and contact, as well as (optionally) an opportunity. 2870apex reference guide database class signature public static database.leadconvertresult convertlead(database.leadconvert leadtoconvert, boolean allornone, system.accesslevel accesslevel) parameters leadtoconvert type: database.leadconvert allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. 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: database.leadconvertresult usage the convertlead |
method accepts up to 100 leadconvert objects. each executed convertlead method counts against the governor limit for dml statements. convertlead(leadstoconvert, allornone, accesslevel) converts a list of leadconvert objects into accounts and contacts, as well as (optionally) opportunities. signature public static list<database.leadconvertresult> convertlead(list<database.leadconvert> leadstoconvert, boolean allornone, system.accesslevel accesslevel) parameters leadstoconvert type: list<database.leadconvert> allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter and a record fails, the remainder of the dml operation can still succeed. this method returns a result object that can be used to 2871apex reference guide database class verify which records succeeded, which failed, and why. if the parameter is not set or is set true, an exception is thrown if the method is not successful. 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: list<database.leadconvertresult> usage the convertlead method accepts up to 100 leadconvert objects. each executed convertlead method counts against the governor limit for dml statements. convertlead(leadtoconvert, dmloptions, accesslevel) converts a lead into an account and contact, as well as (optionally) an opportunity. signature public static database.leadconvertresult convertlead(database.leadconvert leadtoconvert, database.dmloptions dmloptions, system.accesslevel accesslevel) parameters leadtoconvert type: database.leadconvert dmloptions type: database.dmloptions the optional dmloptions parameter specifies additional data for the transaction, such as assignment rule information or rollback behavior when errors occur during record insertions. 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: database.leadconvertresult 2872apex reference guide database class usage the convertlead method accepts up to 100 leadconvert objects. each executed convertlead method counts against the governor limit for dml statements. convertlead(leadstoconvert, dmloptions, accesslevel) converts a list of leadconvert objects into accounts and contacts, as well as (optionally) opportunities. signature public static list<database.leadconvertresult> convertlead(list<database.leadconvert> leadstoconvert, database.dmloptions dmloptions, system.accesslevel accesslevel) parameters leadstoconvert type: list<database.leadconvert> dmloptions type: database.dmloptions the optional dmloptions parameter specifies additional data for the transaction, such as assignment rule information or rollback behavior when errors occur during record insertions. 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: list<database.leadconvertresult> usage the convertlead method accepts up to 100 leadconvert objects. each executed convertlead method counts against the governor limit for dml statements. countquery(query) returns the number of records that a dynamic soql query would |
return when executed. signature public static integer countquery(string query) 2873apex reference guide database class parameters query type: string return value type: integer usage for more information, see dynamic soql. each executed countquery method counts against the governor limit for soql queries. example string querystring = 'select count() from account'; integer i = database.countquery(querystring); countquery(query, accesslevel) returns the number of records that a dynamic soql query would return when executed. signature public static integer countquery(string query, system.accesslevel accesslevel) parameters query type: 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: integer usage for more information, see dynamic soql. each executed countquery method counts against the governor limit for soql queries. 2874apex reference guide database class countquerywithbinds(query, bindmap, accesslevel) returns the number of records that a dynamic soql query would return when executed. bind variables in the query are resolved from the bindmap map parameter directly with the key, rather than from apex code variables. signature public static integer countquerywithbinds(string query, map<string, object> bindmap, system.accesslevel accesslevel) parameters query type: string soql query that includes apex bind variables preceded by a colon. all bind variables must have a key in the bindmap map. bindmap type: map<string, object> a map that contains keys for each bind variable specified in the soql querystring and its value. the keys can’t be null or duplicates, and the values can’t be null or empty strings. accesslevel type: system.accesslevel 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. return value type: integer usage for more information, see dynamic soql. each executed countquerywithbinds method counts against the governor limit for soql queries. example in this example, the soql query uses a bind variable for an account name. its value (acme inc.) is passed in to the method using the namebind map. the accountname variable isn't (and doesn’t have to be) in scope when the query is executed within the method. public static integer simplebindingsoqlquery(map<string, object> bindparams) { string querystring = 'select count() ' + 'from account ' + 'where name = :name'; return database.countquerywithbinds( querystring, bindparams, 2875apex reference guide database class accesslevel.user_mode ); } string accountname = 'acme inc.'; map<string, object> namebind = new map<string, object>{'name' => accountname}; integer acctcount = simplebindingsoqlquery(namebind); system.debug(acctcount); delete(recordtodelete, allornone) deletes an existing sobject record, such as an individual account or contact, from your organization's data. signature public static database.deleteresult delete(sobject recordtodelete, boolean allornone) parameters recordtodelete type: sobject allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. return value type: database.deleteresult usage delete is analogous |
to the delete() statement in the soap api. each executed delete method counts against the governor limit for dml statements. delete(recordstodelete, allornone) deletes a list of existing sobject records, such as individual accounts or contacts, from your organization’s data. signature public static database.deleteresult[] delete(sobject[] recordstodelete, boolean allornone) parameters recordstodelete type: sobject[] 2876apex reference guide database class allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. return value type: database.deleteresult[] usage delete is analogous to the delete() statement in the soap api. each executed delete method counts against the governor limit for dml statements. example the following example deletes an account named 'dotcom': account[] doomedaccts = [select id, name from account where name = 'dotcom']; database.deleteresult[] dr_dels = database.delete(doomedaccts); delete(recordid, allornone) deletes existing sobject records, such as individual accounts or contacts, from your organization’s data. signature public static database.deleteresult delete(id recordid, boolean allornone) parameters recordid type: id allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. return value type: database.deleteresult usage delete is analogous to the delete() statement in the soap api. 2877apex reference guide database class each executed delete method counts against the governor limit for dml statements. delete(recordids, allornone) deletes a list of existing sobject records, such as individual accounts or contacts, from your organization’s data. signature public static database.deleteresult[] delete(id[] recordids, boolean allornone) parameters recordids type: id[] allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. return value type: database.deleteresult[] usage delete is analogous to the delete() statement in the soap api. each executed delete method counts against the governor limit for dml statements. delete(recordtodelete, allornone, accesslevel) deletes an existing sobject record, such as an individual account or contact, from your organization's data. signature public static database.deleteresult delete(sobject recordtodelete, boolean allornone, system.accesslevel accesslevel) parameters recordtodelete type: sobject allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. 2878apex reference guide database class 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: database |
.deleteresult usage delete is analogous to the delete() statement in the soap api. each executed delete method counts against the governor limit for dml statements. delete(recordstodelete, allornone, accesslevel) deletes a list of existing sobject records, such as individual accounts or contacts, from your organization’s data. signature public static list<database.deleteresult> delete(list<sobject> recordstodelete, boolean allornone, system.accesslevel accesslevel) parameters recordstodelete type: list<sobject> allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. 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: list<database.deleteresult> 2879apex reference guide database class usage delete is analogous to the delete() statement in the soap api. each executed delete method counts against the governor limit for dml statements. delete(recordid, allornone, accesslevel) deletes existing sobject records, such as individual accounts or contacts, from your organization’s data. signature public static database.deleteresult delete(id recordid, boolean allornone, system.accesslevel accesslevel) parameters recordid type: id allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. 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: database.deleteresult usage delete is analogous to the delete() statement in the soap api. each executed delete method counts against the governor limit for dml statements. delete(recordids, allornone, accesslevel) deletes a list of existing sobject records, such as individual accounts or contacts, from your organization’s data. signature public static list<database.deleteresult> delete(list<id> recordids, boolean allornone, system.accesslevel accesslevel) 2880apex reference guide database class parameters recordids type: list<id> allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. 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: list<database.deleteresult> usage delete is analogous |
to the delete() statement in the soap api. each executed delete method counts against the governor limit for dml statements. deleteasync(sobjects, callback) initiates requests to delete the external data that corresponds to the specified external object records. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. allows referencing a callback class whose processdelete method is called for each record after deletion. signature public static list<database.deleteresult> deleteasync(list<sobject> sobjects, datasource.asyncdeletecallback callback) parameters sobjects type: list<sobject> list of external object records to delete. callback type: datasource.asyncdeletecallback the callback that contains the state in the originating context and an action (the processdelete method) that is executed after the insert operation is completed. use the action callback to update org data according to the operation’s results. the callback object must extend datasource.asyncdeletecallback. 2881apex reference guide database class return value type: list<database.deleteresult> status results for the delete operation. each result corresponds to a record processed by this asynchronous operation and is associated with a unique identifier (asynclocator). the asynclocator value is included in the errors array of the result. you can retrieve this identifier with database.getasynclocator(). retrieve the final result with database.getasyncdeleteresult(). deleteasync(sobject, callback) initiates a request to delete the external data that corresponds to the specified external object record. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. allows referencing a callback class whose processdelete method is called after deletion. signature public static database.deleteresult deleteasync(sobject sobject, datasource.asyncdeletecallback callback) parameters sobject type: sobject the external object record to delete. callback type: datasource.asyncdeletecallback the callback that contains the state in the originating context and an action (the processdelete method) that is executed after the insert operation is completed. use the action callback to update org data according to the operation’s results. the callback object must extend datasource.asyncdeletecallback. return value type: database.deleteresult status result for the delete operation. the result corresponds to the record processed by this asynchronous operation and is associated with a unique identifier (asynclocator). the asynclocator value is included in the errors array of the result. you can retrieve this identifier with database.getasynclocator(). retrieve the final result with database.getasyncdeleteresult(). deleteasync(sobjects) initiates requests to delete the external data that corresponds to the specified external object records. the requests are executed asynchronously, as background operations, and are sent to the external systems that are defined by the external objects' associated external data sources. signature public static list<database.deleteresult> deleteasync(list<sobject> sobjects) 2882 |
apex reference guide database class parameters sobjects type: list<sobject> list of external object records to delete. return value type: list<database.deleteresult> status results for the delete operation. each result corresponds to a record processed by this asynchronous operation and is associated with a unique identifier (asynclocator). the asynclocator value is included in the errors array of the result. you can retrieve this identifier with database.getasynclocator(). retrieve the final result with database.getasyncdeleteresult(). deleteasync(sobject) initiates a request to delete the external data that corresponds to the specified external object record. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. signature public static database.deleteresult deleteasync(sobject sobject) parameters sobject type: sobject the external object record to delete. return value type: database.deleteresult status result for the delete operation. the result corresponds to the record processed by this asynchronous operation and is associated with a unique identifier (asynclocator). the asynclocator value is included in the errors array of the result. you can retrieve this identifier with database.getasynclocator(). retrieve the final result with database.getasyncdeleteresult(). deleteasync(sobjects, callback, accesslevel) initiates requests to delete the external data that corresponds to the specified external object records. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. allows referencing a callback class whose processdelete method is called for each record after deletion. signature public static list<database.deleteresult> deleteasync(list<sobject> sobjects, datasource.asyncdeletecallback callback, system.accesslevel accesslevel) 2883apex reference guide database class parameters sobjects type: list<sobject> list of external object records to delete. callback type: datasource.asyncdeletecallback the callback that contains the state in the originating context and an action (the processdelete method) that is executed after the insert operation is completed. the execution is in system mode regardless of the accesslevel parameter. use the action callback to update org data according to the operation’s results. the callback object must extend datasource.asyncdeletecallback. 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: list<database.deleteresult> status results for the delete operation. each result corresponds to a record processed by this asynchronous operation and is associated with a unique identifier (asynclocator). the asynclocator value is included in the errors array of the result. you can retrieve this identifier with database.getasynclocator(). retrieve the final result with database.getasyncdeleteresult(). deleteasync(sobject, callback, accesslevel) initiates a request to delete the external data that corresponds to the specified external object record. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. allows referencing a callback class whose processdelete method is called after deletion. signature public static database.deleteresult deleteasync(sobject sobject, datasource.asyncdeletecallback callback, system.accesslevel accesslevel) parameters sobject type: sobject the external object record to delete. callback type: datasource.asyncdeletecallback the callback that contains the state in the originating context and an action (the processdelete method) that is executed after the insert operation is completed. the execution is in system mode regardless of the accesslevel parameter. use the action callback to update org data according to the operation’s results. the callback object must extend datasource.asyncdeletecallback. 2884apex reference guide database class 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: database.deleteresult status result for the delete operation. the result corresponds to the record processed by this asynchronous operation and is associated with a unique identifier (asynclocator). the asynclocator value is included in the errors array of the result. you can retrieve this identifier with database.getasynclocator(). retrieve the final result with database.getasyncdeleteresult(). deleteasync(sobjects, accesslevel) initiates requests to delete the external data that corresponds to the specified external object records. the requests are executed asynchronously, as background operations, and are sent to the external systems that are defined by the external objects' associated external data sources. signature public static list<database.deleteresult> deleteasync(list<sobject> sobjects, system.accesslevel accesslevel) parameters sobjects type: list<sobject> list of external object records to delete. 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: list<database.deleteresult> status results for the delete operation. each result corresponds to a record processed by this asynchronous operation and is associated with a unique identifier (asynclocator). the asynclocator value is included in the errors array of the result. you can retrieve this identifier with database.getasynclocator(). retrieve the final result with database.getasyncdeleteresult(). 2885apex reference guide database class deleteasync(sobject, accesslevel) initiates a request to delete the external data that corresponds to the specified external object record. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. signature public static database.deleteresult deleteasync(sobject sobject, system.accesslevel accesslevel) parameters sobject type: sobject the external object record to delete. 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: database.deleteresult status result for the delete operation. the result corresponds to the record processed by this asynchronous operation and is associated with a unique identifier (asynclocator). the asynclocator value is included in the errors array of the result. you can retrieve this identifier with database.getasynclocator(). retrieve the final result with database.getasyncdeleteresult(). deleteimmediate(sobjects) initiates requests to delete the external data that corresponds to the specified external object records. the requests are executed synchronously and are sent to the external systems that are defined by the external objects' associated external data sources. if the apex transaction contains pending changes, the synchronous operations can't be completed and throw exceptions. signature public static list<database.deleteresult> deleteimmediate(list<sobject> sobjects) parameters sobjects type: list<sobject> list of external object records to delete. return value type: list<database.deleteresult> 2886apex reference guide database class status results for the delete operation. usage the batch limit for big objects using deleteimmediate() is 50,000 records at once. deleteimmediate(sobject) initiates a request to delete the external data that corresponds to the specified external object record. the request is executed synchronously and is sent to the external system that's defined by the external object's associated external data source. if the apex transaction contains |
pending changes, the synchronous operation can't be completed and throws an exception. signature public static database.deleteresult deleteimmediate(sobject sobject) parameters sobject type: sobject the external object record to delete. return value type: database.deleteresult status result for the delete operation. deleteimmediate(sobjects, accesslevel) initiates requests to delete the external data that corresponds to the specified external object records. the requests are executed synchronously and are sent to the external systems that are defined by the external objects' associated external data sources. if the apex transaction contains pending changes, the synchronous operations can't be completed and throw exceptions. signature public static list<database.deleteresult> deleteimmediate(list<sobject> sobjects, system.accesslevel accesslevel) parameters sobjects type: list<sobject> list of external object records to delete. 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. 2887apex reference guide database class return value type: list<database.deleteresult> status results for the delete operation. usage the batch limit for big objects using deleteimmediate() is 50,000 records at once. deleteimmediate(sobject, accesslevel) initiates a request to delete the external data that corresponds to the specified external object record. the request is executed synchronously and is sent to the external system that's defined by the external object's associated external data source. if the apex transaction contains pending changes, the synchronous operation can't be completed and throws an exception. signature public static database.deleteresult deleteimmediate(sobject sobject, system.accesslevel accesslevel) parameters sobject type: sobject the external object record to delete. 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: database.deleteresult status result for the delete operation. emptyrecyclebin(recordids) permanently deletes the specified records from the recycle bin. signature public static database.emptyrecyclebinresult[] emptyrecyclebin(id [] recordids) parameters recordids type: id[] 2888apex reference guide database class return value type: database.emptyrecyclebinresult[] usage note the following: • after records are deleted using this method, they cannot be undeleted. • only 10,000 records can be specified for deletion. • logged in users can delete any record that they can query in their recycle bin, or the recycle bins of any subordinates. if logged in users have “modify all data” permission, they can query and delete records from any recycle bin in the organization. • cascade delete record ids should not be included in the list of ids; otherwise an error occurs. for example, if an account record is deleted, all related contacts, opportunities, contracts, and so on are also deleted. only include the id of the top-level account. all related records are automatically removed. • deleted items are added to the number of items processed by a dml statement, and the method call is added to the total number of dml statements issued. each executed emptyrecyclebin method counts against the governor limit for dml statements. emptyrecyclebin(obj) permanently deletes the specified sobject from the recycle bin. signature public static database.emptyrecyclebinresult emptyrecyclebin(sobject obj) parameters obj type: sobject return value type: database.emptyrecyclebinresult usage note the following: • after an sobject is deleted using |
this method, it cannot be undeleted. • only 10,000 sobjects can be specified for deletion. • the logged-in user can delete any sobject (that can be queried) in their recycle bin, or the recycle bins of any subordinates. if the logged-in user has “modify all data” permission, they can query and delete sobjects from any recycle bin in the organization. • do not include an sobject that was deleted due to a cascade delete; otherwise an error occurs. for example, if an account is deleted, all related contacts, opportunities, contracts, and so on are also deleted. only include sobjects of the top-level account. all related sobjects are automatically removed. emptyrecyclebin(listofsobjects) permanently deletes the specified sobjects from the recycle bin. 2889apex reference guide database class signature public static database.emptyrecyclebinresult[] emptyrecyclebin(sobject[] listofsobjects) parameters listofsobjects type: sobject[] return value type: database.emptyrecyclebinresult[] usage note the following: • after an sobject is deleted using this method, it cannot be undeleted. • only 10,000 sobjects can be specified for deletion. • the logged-in user can delete any sobject (that can be queried) in their recycle bin, or the recycle bins of any subordinates. if the logged-in user has “modify all data” permission, they can query and delete sobjects from any recycle bin in the organization. • do not include an sobject that was deleted due to a cascade delete; otherwise an error occurs. for example, if an account is deleted, all related contacts, opportunities, contracts, and so on are also deleted. only include sobjects of the top-level account. all related sobjects are automatically removed. executebatch(batchclassobject) submits a batch apex job for execution corresponding to the specified class. signature public static id executebatch(object batchclassobject) parameters batchclassobject type: object an instance of a class that implements the database.batchable interface. return value type: id the id of the new batch job (asyncapexjob). usage when calling this method, salesforce chunks the records returned by the start method of the batch class into batches of 200, and then passes each batch to the execute method. apex governor limits are reset for each execution of execute. for more information, see using batch apex. 2890apex reference guide database class versioned behavior changes if the executebatch call fails to acquire an apex flex queue lock: • in api version 52.0 and later, the call throws a system.asyncexception. • in api version 51.0 and earlier, the call returns an empty id, "000000000000000", instead of throwing an exception. executebatch(batchclassobject, scope) submits a batch apex job for execution using the specified class and scope. signature public static id executebatch(object batchclassobject, integer scope) parameters batchclassobject type: object an instance of a class that implements the database.batchable interface. scope type: integer number of records to be passed into the execute method for batch processing. return value type: id the id of the new batch job (asyncapexjob). usage the value for scope must be greater than 0. if the start method of the batch class returns a database.querylocator, the scope parameter of database.executebatch can have a maximum value of 2,000. if set to a higher value, salesforce chunks the records returned by the querylocator into smaller batches of up to 200 records. if the start method of the batch class returns an iterable, the scope parameter value has no upper limit; however, if you use a very high number, you could run into other limits. apex governor limits are reset for each execution of execute. for more information, see using batch apex. versioned behavior changes if the executebatch call fails to acquire an apex flex queue lock: • in api version 52.0 and later, the call throws a system.asyncexception. • in api version 51.0 and earlier, the call returns an empty id, "000000000000000", instead of throwing an exception. getasyncdeleteresult(deleteresult) retrieves the status of an asynchronous delete operation that’s identified by a database.deleteresult object. |
2891apex reference guide database class signature public static database.deleteresult getasyncdeleteresult(database.deleteresult deleteresult) parameters deleteresult type: database.deleteresult the result record for the delete operation being retrieved. return value type: database.deleteresult the result of a completed asynchronous delete of a record or records. getasyncdeleteresult(asynclocator) retrieves the result of an asynchronous delete operation based on the result’s unique identifier. signature public static database.deleteresult getasyncdeleteresult(string asynclocator) parameters asynclocator type: string the unique identifier associated with the result of an asynchronous operation. return value type: database.deleteresult the result of a completed asynchronous delete of a record or records. getasynclocator(result) returns the asynclocator associated with the result of a specified asynchronous insert, update, or delete operation. signature public static string getasynclocator(object result) parameters result type: object the saved result of an asynchronous insert, update, or delete operation. the result object can be of type database.saveresult or database.deleteresult. 2892apex reference guide database class return value type: string the unique identifier associated with the result of the specified operation. getasyncsaveresult(saveresult) returns the status of an asynchronous insert or update operation that’s identified by a database.saveresult object. signature public static database.saveresult getasyncsaveresult(database.saveresult saveresult) parameters saveresult type: database.saveresult the result record for the insert or update operation being retrieved. return value database.saveresult the result of a completed asynchronous operation on a record or records. getasyncsaveresult(asynclocator) returns the status of an asynchronous insert or update operation based on the unique identifier associated with each modification. signature public static database.saveresult getasyncsaveresult(string asynclocator) parameters asynclocator type: string the unique identifier associated with the result of an asynchronous operation. return value database.saveresult the result of a completed asynchronous operation on a record or records. getdeleted(sobjecttype, startdate, enddate) returns the list of individual records that have been deleted for an sobject type within the specified start and end dates and times and that are still in the recycle bin. 2893apex reference guide database class signature public static database.getdeletedresult getdeleted(string sobjecttype, datetime startdate, datetime enddate) parameters sobjecttype type: string the sobjecttype argument is the sobject type name for which to get the deleted records, such as account or merchandise__c. startdate type: datetime start date and time of the deleted records time window. enddate type: datetime end date and time of the deleted records time window. return value type: database.getdeletedresult usage because the recycle bin holds records up to 15 days, results are returned for no more than 15 days previous to the day the call is executed (or earlier if an administrator has purged the recycle bin). example database.getdeletedresult r = database.getdeleted( 'merchandise__c', datetime.now().addhours(-1), datetime.now()); getquerylocator(listofqueries) creates a querylocator object used in batch apex or visualforce. signature public static database. querylocator getquerylocator(sobject [] listofqueries) parameters listofqueries type: sobject [] 2894apex reference guide database class return value type: database.querylocator usage you can't use getquerylocator with any query that contains an aggregate function. each executed getquerylocator method counts against the governor limit of 10,000 total records retrieved and the total number of soql queries issued. for more information, see understanding apex managed sharing, and ideastandardsetcontroller class. getquerylocator(query) creates a querylocator object used in batch apex or visualforce. signature public static database.querylocator getquerylocator(string query) parameters query type: string return value type: database.querylocator usage you can't use getquerylocator with any query that contains an aggregate function. each executed getquerylocator method counts against the governor limit of 10,000 total records retrieved and the total |
number of soql queries issued. for more information, see understanding apex managed sharing, and standardsetcontroller class. getquerylocator(listofqueries, accesslevel) creates a querylocator object used in batch apex or visualforce. signature public static database.querylocator getquerylocator(sobject [] listofqueries, system.accesslevel accesslevel) parameters listofqueries type: sobject [] 2895apex reference guide database class 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: database.querylocator usage the access level is evaluated only when the querylocator is created. a querylocator can be long lived, such as when used in a batch. we don’t reevaluate the object and field-level security with each iteration of the querylocator. as a result, if you specify user mode, and then change the security settings after the querylocator is created, the new settings aren’t enforced. you can't use getquerylocator with any query that contains an aggregate function. each executed getquerylocator method counts against the governor limit of 10,000 total records retrieved and the total number of soql queries issued. for more information, see understanding apex managed sharing, and ideastandardsetcontroller class. getquerylocator(query, accesslevel) creates a querylocator object used in batch apex or visualforce. signature public static database.querylocator getquerylocator(string query, system.accesslevel accesslevel) parameters query type: 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: database.querylocator 2896apex reference guide database class usage the access level is evaluated only when the querylocator is created. a querylocator can be long lived, such as when used in a batch. we don’t reevaluate the object and field-level security with each iteration of the querylocator. as a result, if you specify user mode, and then change the security settings after the querylocator is created, the new settings aren’t enforced. you can't use getquerylocator with any query that contains an aggregate function. each executed getquerylocator method counts against the governor limit of 10,000 total records retrieved and the total number of soql queries issued. for more information, see understanding apex managed sharing, and standardsetcontroller class. getquerylocatorwithbinds(query, bindmap, accesslevel) creates a querylocator object used in batch apex or visualforce. bind variables in the query are resolved from the bindmap map parameter directly with the key, rather than from apex code variables. signature public static database.querylocator getquerylocatorwithbinds(string query, map<string, object> bindmap, system.accesslevel accesslevel) parameters query type: string soql query that includes apex bind variables preceded by a colon. all bind variables must have a key in the bindmap map. bindmap type: map<string, object> a map that contains keys for each bind variable specified in the soql querystring and its value. the keys can’t be null or duplicates, and the values can’t be null or empty strings. accesslevel type: system.accesslevel 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. return value type: database.querylocator usage the access level is evaluated only when the querylocator is created. a querylocator can be long lived, such as when used in a batch. we don’t reevaluate the object and field-level security with each iteration of the querylocator. as a result, if you specify user mode, and then change the security settings after the querylocator is created, the new settings aren’t enforced. you can't use getquerylocatorwithbinds with any query that contains an aggregate function. 2897apex reference guide database class each executed getquerylocatorwithbinds method counts against the governor limit for the total number of records retrieved by database.getquerylocator(10,000) and the total number of soql queries issued. see per transaction apex limits. for more information, see understanding apex managed sharing, and standardsetcontroller class. example in this example, the soql query uses a bind variable for an account name. its value (acme corporation) is passed in using the acctbinds map. public class testbatch implements database.batchable<sobject>{ private map<string, object> acctbinds = new map<string, object>{'acctname' => 'acme corporation'}; private string query = 'select id from account where name = :acctname'; public database.querylocator start(database.batchablecontext bc){ return database.getquerylocatorwithbinds(query, acctbinds, accesslevel.user_mode); } public void execute(database.batchablecontext bc, list<sobject> scope){ } public void finish(database.batchablecontext bc){ } } getupdated(sobjecttype, startdate, enddate) returns the list of individual records that have been updated for an sobject type within the specified start and end dates and times. signature public static database.getupdatedresult getupdated(string sobjecttype, datetime startdate, datetime enddate) parameters sobjecttype type: string the sobjecttype argument is the sobject type name for which to get the updated records, such as account or merchandise__c. startdate type: datetime the startdate argument is the start date and time of the updated records time window. enddate type: datetime the enddate argument is the end date and time of the updated records time window. 2898apex reference guide database class return value type: database.getupdatedresult usage the date range for the returned results is no more than 30 days previous to the day the call is executed. example database.getupdatedresult r = database.getupdated( 'merchandise__c', datetime.now().addhours(-1), datetime.now()); insert(recordtoinsert, allornone) adds an sobject, such as an individual account or contact, to your organization's data. signature public static database.saveresult insert(sobject recordtoinsert, boolean allornone) parameters recordtoinsert type: sobject allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. return value type: database.saveresult usage insert is analogous to the insert statement in sql. apex classes and triggers saved (compiled) using api version 15.0 and higher produce a runtime error if you assign a string value that is too long for the field. each executed insert method counts against the governor limit for dml statements. insert(recordstoinsert, allornone) adds one or more sobjects, such as individual accounts or contacts, to your organization’s data. 2899apex reference guide database class signature public static database.saveresult[] insert(sobject[] recordstoinsert, boolean allornone) parameters recordstoinsert type: sobject [] allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter isn’t set or is set true, an exception is thrown if the method isn’t successful. if the parameter is specified as false and a before-trigger assigns an invalid value to a field, the partial set of valid records isn’t inserted. return value type: database.saveresult[] usage insert is analogous to the insert statement in sql. apex classes and triggers saved (compiled) using api version 15.0 and higher produce a runtime error if you assign a string value that is too long for the field. each executed insert method counts against the governor limit for dml statements. example example: the following example inserts two accounts: account a = new account(name = 'acme1'); database.saveresult[] lsr = database.insert( new account[]{a, new account(name = 'acme2')}, false); insert(recordtoinsert, dmloptions) adds an sobject, such as an individual account or contact, to your organization's data. signature public static database.saveresult insert(sobject recordtoinsert, database.dmloptions dmloptions) parameters recordtoinsert type: sobject 2900apex reference guide database class dmloptions type: database.dmloptions the optional dmloptions parameter specifies additional data for the transaction, such as assignment rule information or rollback behavior when errors occur during record insertions. return value type: database.saveresult usage insert is analogous to the insert statement in sql. apex classes and triggers saved (compiled) using api version 15.0 and higher produce a runtime error if you assign a string value that is too long for the field. each executed insert method counts against the governor limit for dml statements. insert(recordstoinsert, dmloptions) adds one or more sobjects, such as individual accounts or contacts, to your organization's data. signature public static database.saveresult insert(sobject[] recordstoinsert, database.dmloptions dmloptions) parameters recordstoinsert type: sobject[] dmloptions type: database.dmloptions the optional dmloptions parameter specifies additional data for the transaction, such as assignment rule information or rollback behavior when errors occur during record insertions. return value type: database.saveresult[] usage insert is analogous to the insert statement in sql. apex classes and triggers saved (compiled) using api version 15.0 and higher produce a runtime error if you assign a string value that is too long for the field. each executed insert method counts against the governor limit for dml statements. insert(recordtoinsert, allornone, accesslevel) adds an sobject, such as an individual account or contact, to your organization's data. 2901apex reference guide database class signature public static database.saveresult insert(sobject recordtoinsert, boolean allornone, system.accesslevel accesslevel) parameters recordtoinsert type: sobject allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. 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: database.saveresult usage if you use the accesslevel parameter to specify that the method runs in user mode, we report all encountered inaccessible fields. the way to retrieve the names of these inaccessible fields depends on the value of this method's allornone parameter, or the equivalent dmloptions.optallornone property. if you specify that: • allornone=true or dmloptions.optallornone=true: catch the dmlexception and use the dmlex |
ception.getdmlfieldnames() method to retrieve the list of inaccessible fields. see exception class and built-in exceptions for more information. • allornone=false or dmloptions.optallornone=false: for each failing record, we update the database.error object that results from the dml operation. use the error.getfields() method to retrieve the list of inaccessible fields. see the error class methods for more information. insert is analogous to the insert statement in sql. apex classes and triggers saved (compiled) using api version 15.0 and higher produce a runtime error if you assign a string value that is too long for the field. each executed insert method counts against the governor limit for dml statements. insert(recordstoinsert, allornone, accesslevel) adds one or more sobjects, such as individual accounts or contacts, to your organization’s data. 2902apex reference guide database class signature public static list<database.saveresult> insert(list<sobject> recordstoinsert, boolean allornone, system.accesslevel accesslevel) parameters recordstoinsert type: list<sobject> allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter isn’t set or is set true, an exception is thrown if the method isn’t successful. if the parameter is specified as false and a before-trigger assigns an invalid value to a field, the partial set of valid records isn’t inserted. 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: list<database.saveresult> usage if you use the accesslevel parameter to specify that the method runs in user mode, we report all encountered inaccessible fields. the way to retrieve the names of these inaccessible fields depends on the value of this method's allornone parameter, or the equivalent dmloptions.optallornone property. if you specify that: • allornone=true or dmloptions.optallornone=true: catch the dmlexception and use the dmlexception.getdmlfieldnames() method to retrieve the list of inaccessible fields. see exception class and built-in exceptions for more information. • allornone=false or dmloptions.optallornone=false: for each failing record, we update the database.error object that results from the dml operation. use the error.getfields() method to retrieve the list of inaccessible fields. see the error class methods for more information. insert is analogous to the insert statement in sql. apex classes and triggers saved (compiled) using api version 15.0 and higher produce a runtime error if you assign a string value that is too long for the field. each executed insert method counts against the governor limit for dml statements. insert(recordtoinsert, dmloptions, accesslevel) adds an sobject, such as an individual account or contact, to your organization's data. 2903apex reference guide database class signature public static database.saveresult insert(sobject recordtoinsert, database.dmloptions dmloptions, system.accesslevel accesslevel) parameters recordtoinsert type: sobject dmloptions type: database.dmloptions the optional dmloptions parameter specifies additional data for the transaction, such as assignment rule information or rollback behavior when errors occur during record insertions. 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: database.saveresult usage insert is analogous to the insert statement in sql. apex classes and triggers saved (compiled) using api version 15.0 and higher produce a runtime error if you assign a string value that is too long for the field. each executed insert method counts against the governor limit for dml statements. insert(recordstoinsert, dmloptions, accesslevel) adds one or more sobjects, such as individual accounts or contacts, to your organization's data. signature public static list<database.saveresult> insert(list<sobject> recordstoinsert, database.dmloptions dmloptions, system.accesslevel accesslevel) parameters recordstoinsert type: list<sobject> dmloptions type: database.dmloptions the optional dmloptions parameter specifies additional data for the transaction, such as assignment rule information or rollback behavior when errors occur during record insertions. 2904apex reference guide database class 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: list<database.saveresult> usage insert is analogous to the insert statement in sql. apex classes and triggers saved (compiled) using api version 15.0 and higher produce a runtime error if you assign a string value that is too long for the field. each executed insert method counts against the governor limit for dml statements. insertasync(sobjects, callback) initiates requests to add external object data to the relevant external systems. the requests are executed asynchronously, as background operations, and are sent to the external systems that are defined by the external objects' associated external data sources. allows referencing a callback class whose processsave method is called for each record after the remote operations are completed. signature public static list<database.saveresult> insertasync(list<sobject> sobjects, datasource.asyncsavecallback callback) parameters sobjects type: list<sobject> list of external object records to insert. callback type: datasource.asyncsavecallback the callback object that contains the state in the originating context and an action (the processsave method) that executes after the insert operation is completed. use the action callback to update org data according to the operation’s results. the callback object must extend datasource.asyncsavecallback. return value type: list<database.saveresult> status results for the insert operation. each result corresponds to a record processed by this asynchronous operation and is associated with a unique identifier (asynclocator). the asynclocator value is included in the errors array of the result. you can retrieve this identifier with database.getasynclocator(). retrieve the final result with database.getasyncsaveresult(). 2905apex reference guide database class usage database.insertasync() methods can’t be executed in the context of a portal user, even when the portal user is a community member. to add external object records via apex, use database.insertimmediate() methods. insertasync(sobject, callback) initiates a request to add external object data to the relevant external system. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. allows referencing a callback class whose processsave method is called after the remote operation is completed. signature public static database.saveresult insertasync(sobject sobject, datasource.asyncsavecallback callback) parameters sobject type: sobject the external object record to insert. callback type: datasource.asyncsavecallback the callback object that contains the state in the originating context and an action (the processsave method) that executes after the insert operation is completed. use the action callback to update org data according to the operation’s results. the callback object must extend datasource.asyncsavecallback. return value type: database.saveresult status result for the insert operation. the result corresponds to the record processed by this asynchronous operation and is associated with a unique identifier (asynclocator). the asyncloc |
ator value is included in the errors array of the result. you can retrieve this identifier with database.getasynclocator(). retrieve the final result with database.getasyncsaveresult(). usage database.insertasync() methods can’t be executed in the context of a portal user, even when the portal user is a community member. to add external object records via apex, use database.insertimmediate() methods. insertasync(sobjects) initiates requests to add external object data to the relevant external systems. the requests are executed asynchronously, as background operations, and are sent to the external systems that are defined by the external objects' associated external data sources. signature public static list<database.saveresult> insertasync(list<sobject> sobjects) 2906apex reference guide database class parameters sobjects type: list<sobject> list of external object records to insert. return value type: list<database.saveresult> status results for the insert operation. each result corresponds to a record processed by this asynchronous operation and is associated with a unique identifier (asynclocator). the asynclocator value is included in the errors array of the result. you can retrieve this identifier with database.getasynclocator(). retrieve the final result with database.getasyncsaveresult(). usage database.insertasync() methods can’t be executed in the context of a portal user, even when the portal user is a community member. to add external object records via apex, use database.insertimmediate() methods. insertasync(sobject) initiates a request to add external object data to the relevant external system. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. signature public static database.saveresult insertasync(sobject sobject) parameters sobject type: sobject the external object record to insert. return value type: database.saveresult status result for the insert operation. the result corresponds to the record processed by this asynchronous operation and is associated with a unique identifier (asynclocator). the asynclocator value is included in the errors array of the result. you can retrieve this identifier with database.getasynclocator(). retrieve the final result with database.getasyncsaveresult(). usage database.insertasync() methods can’t be executed in the context of a portal user, even when the portal user is a community member. to add external object records via apex, use database.insertimmediate() methods. insertasync(sobjects, callback, accesslevel) initiates requests to add external object data to the relevant external systems. the requests are executed asynchronously, as background operations, and are sent to the external systems that are defined by the external objects' associated external data sources. allows referencing a callback class whose processsave method is called for each record after the remote operations are completed. 2907apex reference guide database class signature> public static list<database.saveresult> insertasync(list<sobject> sobjects, datasource.asyncsavecallback callback, system.accesslevel accesslevel) parameters> sobjects type: list<sobject> list of external object records to insert. callback type: datasource.asyncsavecallback the callback object that contains the state in the originating context and an action (the processsave method) that executes after the insert operation is completed. the execution is in system mode regardless of the accesslevel parameter. use the action callback to update org data according to the operation’s results. the callback object must extend datasource.asyncsavecallback. 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: list<database.saveresult> status results for the insert operation. each result corresponds to a record processed by this asynchronous operation and is associated with a unique identifier (asynclocator). the asynclocator value is included in the errors array of the result. you can retrieve this identifier with database.getasynclocator(). retrieve the final result with database.getasync |
saveresult(). usage> database.insertasync() methods can’t be executed in the context of a portal user, even when the portal user is a community member. to add external object records via apex, use database.insertimmediate() methods. insertasync(sobject, callback, accesslevel) initiates a request to add external object data to the relevant external system. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. allows referencing a callback class whose processsave method is called after the remote operation is completed. signature public static database.saveresult insertasync(sobject sobject, datasource.asyncsavecallback callback, system.accesslevel accesslevel) 2908apex reference guide database class parameters sobject type: sobject the external object record to insert. callback type: datasource.asyncsavecallback the callback object that contains the state in the originating context and an action (the processsave method) that executes after the insert operation is completed. the execution is in system mode regardless of the accesslevel parameter. use the action callback to update org data according to the operation’s results. the callback object must extend datasource.asyncsavecallback. 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: database.saveresult status result for the insert operation. the result corresponds to the record processed by this asynchronous operation and is associated with a unique identifier (asynclocator). the asynclocator value is included in the errors array of the result. you can retrieve this identifier with database.getasynclocator(). retrieve the final result with database.getasyncsaveresult(). usage database.insertasync() methods can’t be executed in the context of a portal user, even when the portal user is a community member. to add external object records via apex, use database.insertimmediate() methods. insertasync(sobjects, accesslevel) initiates requests to add external object data to the relevant external systems. the requests are executed asynchronously, as background operations, and are sent to the external systems that are defined by the external objects' associated external data sources. signature public static list<database.saveresult> insertasync(list<sobject> sobjects, system.accesslevel accesslevel) parameters sobjects type: list<sobject> list of external object records to insert. accesslevel type: system.accesslevel 2909apex reference guide database class (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: list<database.saveresult> status results for the insert operation. each result corresponds to a record processed by this asynchronous operation and is associated with a unique identifier (asynclocator). the asynclocator value is included in the errors array of the result. you can retrieve this identifier with database.getasynclocator(). retrieve the final result with database.getasyncsaveresult(). usage database.insertasync() methods can’t be executed in the context of a portal user, even when the portal user is a community member. to add external object records via apex, use database.insertimmediate() methods. insertasync(sobject, accesslevel) initiates a request to add external object data to the relevant external system. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. signature public static database.saveresult insertasync(sobject sobject, system.accesslevel accesslevel) parameters sobject type: sobject the external object record to insert. 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: database.saveresult status result for the insert operation. the result corresponds to the record processed by this asynchronous operation and is associated with a unique identifier (asynclocator). the asynclocator value is included in the errors array of the result. you can retrieve this identifier with database.getasynclocator(). retrieve the final result with database.getasyncsaveresult(). 2910apex reference guide database class usage database.insertasync() methods can’t be executed in the context of a portal user, even when the portal user is a community member. to add external object records via apex, use database.insertimmediate() methods. insertimmediate(sobjects) initiates requests to add external object data to the relevant external systems. the requests are executed synchronously and are sent to the external systems that are defined by the external objects' associated external data sources. if the apex transaction contains pending changes, the synchronous operations can't be completed and throw exceptions. signature public static list<database.saveresult> insertimmediate(list<sobject> sobjects) parameters sobjects type: list<sobject> list of external object records to insert. return value type: list<database.saveresult> status results for the insert operation. usage the operation allows partial success. if one or more record inserts fail, the method doesn’t throw an exception and the remainder of the dml operation can still succeed. the returned saveresult objects indicate whether the operation was successful. if it wasn’t successful, the objects also return the error code and description. insertimmediate(sobject) initiates a request to add external object data to the relevant external system. the request is executed synchronously and is sent to the external system that's defined by the external object's associated external data source. if the apex transaction contains pending changes, the synchronous operation can't be completed and throws an exception. signature public static database.saveresult insertimmediate(sobject sobject) parameters sobject type: sobject the external object record to insert. 2911apex reference guide database class return value type: database.saveresult status result for the insert operation. usage if a record insert fails, the method doesn’t throw an exception. the returned saveresult object indicates whether the operation was successful. if it wasn’t successful, the object returns the error code and description. insertimmediate(sobjects, accesslevel) initiates requests to add external object data to the relevant external systems. the requests are executed synchronously and are sent to the external systems that are defined by the external objects' associated external data sources. if the apex transaction contains pending changes, the synchronous operations can't be completed and throw exceptions. signature public static list<database.saveresult> insertimmediate(list<sobject> sobjects, system.accesslevel accesslevel) parameters sobjects type: list<sobject> list of external object records to insert. 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: list<database.saveresult> status results for the insert operation. usage the operation allows partial success. if one or more record inserts fail, the method doesn’t throw an exception and the remainder of the dml operation can still succeed. the returned saveresult objects indicate whether the operation was successful. if it wasn’t successful, the objects also return the error code and description. insertimmediate(sobject, accesslevel) initiates a request to add external object data to the relevant external system. the request is executed synchronously and is |
sent to the external system that's defined by the external object's associated external data source. if the apex transaction contains pending changes, the synchronous operation can't be completed and throws an exception. 2912apex reference guide database class signature public static database.saveresult insertimmediate(sobject sobject, system.accesslevel accesslevel) parameters sobject type: sobject the external object record to insert. 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: database.saveresult status result for the insert operation. usage if a record update fails, the method doesn’t throw an exception. the returned saveresult object indicates whether the operation was successful. if it failed, the object returns the error code and description. merge(masterrecord, duplicateid) merges the specified duplicate record into the master sobject record of the same type, deleting the duplicate, and reparenting any related records. merges only accounts, contacts, or leads. signature public static database.mergeresult merge(sobject masterrecord, id duplicateid) parameters masterrecord type: sobject the master sobject record the duplicate record is merged into. duplicateid type: id the id of the record to merge with the master. this record must be of the same sobject type as the master. return value type: database.mergeresult 2913apex reference guide database class usage each executed merge method counts against the governor limit for dml statements. merge(masterrecord, duplicaterecord) merges the specified duplicate sobject record into the master sobject of the same type, deleting the duplicate, and reparenting any related records. signature public static database.mergeresult merge(sobject masterrecord, sobject duplicaterecord) parameters masterrecord type: sobject the master sobject record the duplicate record is merged into. duplicaterecord type: sobject the sobject record to merge with the master. this sobject must be of the same type as the master. return value type: database.mergeresult usage each executed merge method counts against the governor limit for dml statements. merge(masterrecord, duplicateids) merges up to two records of the same sobject type into the master sobject record, deleting the others, and reparenting any related records. signature public static list<database.mergeresult> merge(sobject masterrecord, list<id> duplicateids) parameters masterrecord type: sobject the master sobject record the other records are merged into. duplicateids type: list<id> a list of ids of up to two records to merge with the master. these records must be of the same sobject type as the master. 2914apex reference guide database class return value type: list<database.mergeresult> usage each executed merge method counts against the governor limit for dml statements. merge(masterrecord, duplicaterecords) merges up to two records of the same object type into the master sobject record, deleting the others, and reparenting any related records. signature public static list<database.mergeresult> merge(sobject masterrecord, list<sobject> duplicaterecords) parameters masterrecord type: sobject the master sobject record the other sobjects are merged into. duplicaterecords type: list<sobject> a list of up to two sobject records to merge with the master. these sobjects must be of the same type as the master. return value type: list<database.mergeresult> usage each executed merge method counts against the governor limit for dml statements. merge(masterrecord, duplicateid, allornone) merges the specified duplicate record into the master sobject record of the same type, optionally returning errors, if any, deleting the duplicate, and reparenting any related records. merges only accounts, contacts, or leads. signature public static database.mergeresult merge( |
sobject masterrecord, id duplicateid, boolean allornone) parameters masterrecord type: sobject the master sobject record the duplicate record is merged into. 2915apex reference guide database class duplicate type: id the id of the record to merge with the master. this record must be of the same sobject type as the master. allornone type: boolean set to false to return any errors encountered in this operation as part of the returned result. if set to true, this method throws an exception if the operation fails. the default is true. return value type: database.mergeresult usage each executed merge method counts against the governor limit for dml statements. merge(masterrecord, duplicaterecord, allornone) merges the specified duplicate sobject record into the master sobject of the same type, optionally returning errors, if any, deleting the duplicate, and reparenting any related records. signature public static database.mergeresult merge(sobject masterrecord, sobject duplicaterecord, boolean allornone) parameters masterrecord type: sobject the master sobject record the duplicate record is merged into. duplicaterecord type: sobject the sobject record to merge with the master. this sobject must be of the same type as the master. allornone type: boolean set to false to return any errors encountered in this operation as part of the returned result. if set to true, this method throws an exception if the operation fails. the default is true. return value type: database.mergeresult usage each executed merge method counts against the governor limit for dml statements. 2916apex reference guide database class merge(masterrecord, duplicateids, allornone) merges up to two records of the same sobject type into the master sobject record, optionally returning errors, if any, deleting the duplicates, and reparenting any related records. signature public static list<database.mergeresult> merge(sobject masterrecord, list<id> duplicateids, boolean allornone) parameters masterrecord type: sobject the master sobject record the other records are merged into. duplicateids type: list<id> a list of ids of up to two records to merge with the master. these records must be of the same sobject type as the master. allornone type: boolean set to false to return any errors encountered in this operation as part of the returned result. if set to true, this method throws an exception if the operation fails. the default is true. return value type: list<database.mergeresult> usage each executed merge method counts against the governor limit for dml statements. merge(masterrecord, duplicaterecords, allornone) merges up to two records of the same object type into the master sobject record, optionally returning errors, if any, deleting the duplicates, and reparenting any related records. signature public static list<database.mergeresult> merge(sobject masterrecord, list<sobject> duplicaterecords, boolean allornone) parameters masterrecord type: sobject the master sobject record the other sobjects are merged into. duplicaterecords type: list<sobject> 2917apex reference guide database class a list of up to two sobject records to merge with the master. these sobjects must be of the same type as the master. allornone type: boolean set to false to return any errors encountered in this operation as part of the returned result. if set to true, this method throws an exception if the operation fails. the default is true. return value type: list<database.mergeresult> usage each executed merge method counts against the governor limit for dml statements. merge(masterrecord, duplicateid, accesslevel) merges the specified duplicate record into the master sobject record of the same type, deleting the duplicate, and reparenting any related records. merges only accounts, contacts, or leads. signature public static database.mergeresult merge(sobject masterrecord, id duplicateid, system.accesslevel accesslevel) parameters masterrecord type: sobject the master sobject record the duplicate record is merged into. duplicateid type: id the id of the record to merge with the master. this record must be of the same sobject type as the master. accesslevel type: system.access |
level (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: database.mergeresult usage each executed merge method counts against the governor limit for dml statements. 2918apex reference guide database class merge(masterrecord, duplicaterecord, accesslevel) merges the specified duplicate sobject record into the master sobject of the same type, deleting the duplicate, and reparenting any related records. signature public static database.mergeresult merge(sobject masterrecord, sobject duplicaterecord, system.accesslevel accesslevel) parameters masterrecord type: sobject the master sobject record the duplicate record is merged into. duplicaterecord type: sobject the sobject record to merge with the master. this sobject must be of the same type as the master. 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: database.mergeresult usage each executed merge method counts against the governor limit for dml statements. merge(masterrecord, duplicateids, accesslevel) merges up to two records of the same sobject type into the master sobject record, deleting the others, and reparenting any related records. signature public static list<database.mergeresult> merge(sobject masterrecord, list<id> duplicateids, system.accesslevel accesslevel) parameters masterrecord type: sobject the master sobject record the other records are merged into. 2919apex reference guide database class duplicateids type: list<id> a list of ids of up to two records to merge with the master. these records must be of the same sobject type as the master. 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: list<database.mergeresult> usage each executed merge method counts against the governor limit for dml statements. merge(masterrecord, duplicaterecords, accesslevel) merges up to two records of the same object type into the master sobject record, deleting the others, and reparenting any related records. signature public static list<database.mergeresult> merge(sobject masterrecord, list<sobject> duplicaterecords, system.accesslevel accesslevel) parameters masterrecord type: sobject the master sobject record the other sobjects are merged into. duplicaterecords type: list<sobject> a list of up to two sobject records to merge with the master. these sobjects must be of the same type as the master. 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: list<database.mergeresult> 2920apex reference guide database class usage each executed merge method counts against the governor limit for dml statements. merge(masterrecord |
, duplicateid, allornone, accesslevel) merges the specified duplicate record into the master sobject record of the same type, optionally returning errors, if any, deleting the duplicate, and reparenting any related records. merges only accounts, contacts, or leads. signature public static database.mergeresult merge(sobject masterrecord, id duplicateid, boolean allornone, system.accesslevel accesslevel) parameters masterrecord type: sobject the master sobject record the duplicate record is merged into. duplicateid type: id the id of the record to merge with the master. this record must be of the same sobject type as the master. allornone type: boolean set to false to return any errors encountered in this operation as part of the returned result. if set to true, this method throws an exception if the operation fails. the default is true. 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: database.mergeresult usage if you use the accesslevel parameter to specify that the method runs in user mode, we report all encountered inaccessible fields. the way to retrieve the names of these inaccessible fields depends on the value of this method's allornone parameter, or the equivalent dmloptions.optallornone property. if you specify that: • allornone=true or dmloptions.optallornone=true: catch the dmlexception and use the dmlexception.getdmlfieldnames() method to retrieve the list of inaccessible fields. see exception class and built-in exceptions for more information. 2921apex reference guide database class • allornone=false or dmloptions.optallornone=false: for each failing record, we update the database.error object that results from the dml operation. use the error.getfields() method to retrieve the list of inaccessible fields. see the error class methods for more information. each executed merge method counts against the governor limit for dml statements. merge(masterrecord, duplicaterecord, allornone, accesslevel) merges the specified duplicate sobject record into the master sobject of the same type, optionally returning errors, if any, deleting the duplicate, and reparenting any related records. signature public static database.mergeresult merge(sobject masterrecord, sobject duplicaterecord, boolean allornone, system.accesslevel accesslevel) parameters masterrecord type: sobject the master sobject record the duplicate record is merged into. duplicaterecord type: sobject the sobject record to merge with the master. this sobject must be of the same type as the master. allornone type: boolean set to false to return any errors encountered in this operation as part of the returned result. if set to true, this method throws an exception if the operation fails. the default is true. 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: database.mergeresult usage if you use the accesslevel parameter to specify that the method runs in user mode, we report all encountered inaccessible fields. the way to retrieve the names of these inaccessible fields depends on the value of this method's allornone parameter, or the equivalent dmloptions.optallornone property. if you specify that: • allornone=true or dmloptions.optallornone=true: catch the dmlexception and use the dmlexception.getdmlfieldnames() method to retrieve the list of inaccessible fields. see exception class and built-in exceptions for more information. 2922apex reference guide database class • allornone=false or dmloptions. |
optallornone=false: for each failing record, we update the database.error object that results from the dml operation. use the error.getfields() method to retrieve the list of inaccessible fields. see the error class methods for more information. each executed merge method counts against the governor limit for dml statements. merge(masterrecord, duplicateids, allornone, accesslevel) merges up to two records of the same sobject type into the master sobject record, optionally returning errors, if any, deleting the duplicates, and reparenting any related records. signature public static list<database.mergeresult> merge(sobject masterrecord, list<id> duplicateids, boolean allornone, system.accesslevel accesslevel) parameters masterrecord type: sobject the master sobject record the other records are merged into. duplicateids type: list<id> a list of ids of up to two records to merge with the master. these records must be of the same sobject type as the master. allornone type: boolean set to false to return any errors encountered in this operation as part of the returned result. if set to true, this method throws an exception if the operation fails. the default is true. 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: list<database.mergeresult> usage if you use the accesslevel parameter to specify that the method runs in user mode, we report all encountered inaccessible fields. the way to retrieve the names of these inaccessible fields depends on the value of this method's allornone parameter, or the equivalent dmloptions.optallornone property. if you specify that: • allornone=true or dmloptions.optallornone=true: catch the dmlexception and use the dmlexception.getdmlfieldnames() method to retrieve the list of inaccessible fields. see exception class and built-in exceptions for more information. 2923apex reference guide database class • allornone=false or dmloptions.optallornone=false: for each failing record, we update the database.error object that results from the dml operation. use the error.getfields() method to retrieve the list of inaccessible fields. see the error class methods for more information. each executed merge method counts against the governor limit for dml statements. merge(masterrecord, duplicaterecords, allornone, accesslevel) merges up to two records of the same object type into the master sobject record, optionally returning errors, if any, deleting the duplicates, and reparenting any related records. signature public static list<database.mergeresult> merge(sobject masterrecord, list<sobject> duplicaterecords, boolean allornone, system.accesslevel accesslevel) parameters masterrecord type: sobject the master sobject record the other sobjects are merged into. duplicaterecords type: list<sobject> a list of up to two sobject records to merge with the master. these sobjects must be of the same type as the master. allornone type: boolean set to false to return any errors encountered in this operation as part of the returned result. if set to true, this method throws an exception if the operation fails. the default is true. 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: list<database.mergeresult> usage if you use the accesslevel parameter to specify that the method runs in user mode, we report all encountered inaccessible fields. the way to retrieve the names of these inaccessible fields depends on the value of |
this method's allornone parameter, or the equivalent dmloptions.optallornone property. if you specify that: • allornone=true or dmloptions.optallornone=true: catch the dmlexception and use the dmlexception.getdmlfieldnames() method to retrieve the list of inaccessible fields. see exception class and built-in exceptions for more information. 2924apex reference guide database class • allornone=false or dmloptions.optallornone=false: for each failing record, we update the database.error object that results from the dml operation. use the error.getfields() method to retrieve the list of inaccessible fields. see the error class methods for more information. each executed merge method counts against the governor limit for dml statements. query(querystring) creates a dynamic soql query at runtime. signature public static list<sobject> query(string querystring) parameters querystring type: string return value type: list on page 3123<sobject> usage this method can be used wherever a static soql query can be used, such as in regular assignment statements and for loops. unlike inline soql, fields in bind variables are not supported. for more information, see dynamic soql. each executed query method counts against the governor limit for soql queries. query(querystring, accesslevel) creates a dynamic soql query at runtime. signature public static list<sobject> query(string querystring, system.accesslevel accesslevel) parameters querystring type: 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. 2925apex reference guide database class return value type: list on page 3123<sobject> usage this method can be used wherever a static soql query can be used, such as in regular assignment statements and for loops. unlike inline soql, fields in bind variables are not supported. for more information, see dynamic soql. each executed query method counts against the governor limit for soql queries. querywithbinds(querystring, bindmap, accesslevel) creates a dynamic soql query at runtime. bind variables in the query are resolved from the bindmap map parameter directly with the key, rather than from apex code variables. signature public static list<sobject> querywithbinds(string querystring, map<string, object> bindmap, system.accesslevel accesslevel) parameters querystring type: string soql query that includes apex bind variables or expressions preceded by a colon. all bind variables must have a key in the bindmap map. bindmap type: map<string, object> a map that contains keys for each bind variable specified in the soql querystring and its value. the keys can’t be null or duplicates, and the values can’t be null or empty strings. accesslevel type: system.accesslevel 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. return value type: list on page 3123<sobject> usage this method can be used wherever a static soql query can be used, such as in regular assignment statements and for loops. for more information, see dynamic soql. each executed querywithbinds method counts against the governor limit for soql queries. 2926apex reference guide database class example in this example, the soql query uses a bind variable for an account name. its value (acme inc.) is passed in to the method using the namebind map. the accountname variable isn't (and doesn’t have to be) in scope when the query is executed within the method. public static list<account> simplebindingsoqlquery(map<string, object> bindparams) { string |
querystring = 'select id, name ' + 'from account ' + 'where name = :name'; return database.querywithbinds( querystring, bindparams, accesslevel.user_mode ); } string accountname = 'acme inc.'; map<string, object> namebind = new map<string, object>{'name' => accountname}; list<account> accounts = simplebindingsoqlquery(namebind); system.debug(accounts); rollback(databasesavepoint) restores the database to the state specified by the savepoint variable. any emails submitted since the last savepoint are also rolled back and not sent. signature public static void rollback(system.savepoint databasesavepoint) parameters databasesavepoint type: system.savepoint return value type: void usage note the following: • static variables are not reverted during a rollback. if you try to run the trigger again, the static variables retain the values from the first run. • each rollback counts against the governor limit for dml statements. you will receive a runtime error if you try to rollback the database additional times. • the id on an sobject inserted after setting a savepoint is not cleared after a rollback. create an sobject to insert after a rollback. attempting to insert the sobject using the variable created before the rollback fails because the sobject variable has an id. updating or upserting the sobject using the same variable also fails because the sobject is not in the database and, thus, cannot be updated. 2927apex reference guide database class for an example, see transaction control. setsavepoint() returns a savepoint variable that can be stored as a local variable, then used with the rollback method to restore the database to that point. signature public static system.savepoint setsavepoint() return value type: system.savepoint usage note the following: • if you set more than one savepoint, then roll back to a savepoint that is not the last savepoint you generated, the later savepoint variables become invalid. for example, if you generated savepoint sp1 first, savepoint sp2 after that, and then you rolled back to sp1, the variable sp2 would no longer be valid. you will receive a runtime error if you try to use it. • references to savepoints cannot cross trigger invocations because each trigger invocation is a new trigger context. if you declare a savepoint as a static variable then try to use it across trigger contexts, you will receive a run-time error. • each savepoint you set counts against the governor limit for dml statements. for an example, see transaction control. undelete(recordtoundelete, allornone) restores an existing sobject record, such as an individual account or contact, from your organization's recycle bin. signature public static database.undeleteresult undelete(sobject recordtoundelete, boolean allornone) parameters recordtoundelete type: sobject allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. return value type: database.undeleteresult 2928apex reference guide database class usage undelete is analogous to the undelete statement in sql. each executed undelete method counts against the governor limit for dml statements. undelete(recordstoundelete, allornone) restores one or more existing sobject records, such as individual accounts or contacts, from your organization’s recycle bin. signature public static database.undeleteresult[] undelete(sobject[] recordstoundelete, boolean allornone) parameters recordstoundelete type: sobject [] allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not |
successful. return value type: database.undeleteresult[] usage undelete is analogous to the undelete statement in sql. each executed undelete method counts against the governor limit for dml statements. example the following example restores all accounts named 'universal containers'. the all rows keyword queries all rows for both top-level and aggregate relationships, including deleted records and archived activities. account[] savedaccts = [select id, name from account where name = 'universal containers' all rows]; database.undeleteresult[] udr_dels = database.undelete(savedaccts); undelete(recordid, allornone) restores an existing sobject record, such as an individual account or contact, from your organization's recycle bin. 2929apex reference guide database class signature public static database.undeleteresult undelete(id recordid, boolean allornone) parameters recordid type: id allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. return value type: database.undeleteresult usage undelete is analogous to the undelete statement in sql. each executed undelete method counts against the governor limit for dml statements. undelete(recordids, allornone) restores one or more existing sobject records, such as individual accounts or contacts, from your organization’s recycle bin. signature public static database.undeleteresult[] undelete(id[] recordids, boolean allornone) parameters recordids type: id[] allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. return value type: database.undeleteresult[] 2930apex reference guide database class usage undelete is analogous to the undelete statement in sql. each executed undelete method counts against the governor limit for dml statements. undelete(recordtoundelete, allornone, accesslevel) restores an existing sobject record, such as an individual account or contact, from your organization's recycle bin. signature public static database.undeleteresult undelete(sobject recordtoundelete, boolean allornone, system.accesslevel accesslevel) parameters recordtoundelete type: sobject allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. 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: database.undeleteresult usage undelete is analogous to the undelete statement in sql. each executed undelete method counts against the governor limit for dml statements. undelete(recordstoundelete, allornone, accesslevel) restores one or more existing sobject records, such as individual accounts or contacts, from your organization’s recycle bin. signature public static list<database.undeleteresult> undelete(list<sobject> recordstoundelete, boolean allornone, system.accesslevel accesslevel) 2931 |
apex reference guide database class parameters recordstoundelete type: list<sobject> allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. 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: list<database.undeleteresult> usage undelete is analogous to the undelete statement in sql. each executed undelete method counts against the governor limit for dml statements. undelete(recordid, allornone, accesslevel) restores an existing sobject record, such as an individual account or contact, from your organization's recycle bin. signature public static database.undeleteresult undelete(id recordid, boolean allornone, system.accesslevel accesslevel) parameters recordid type: id allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. accesslevel type: system.accesslevel 2932 |
apex reference guide database class (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: database.undeleteresult usage undelete is analogous to the undelete statement in sql. each executed undelete method counts against the governor limit for dml statements. undelete(recordids, allornone, accesslevel) restores one or more existing sobject records, such as individual accounts or contacts, from your organization’s recycle bin. signature public static list<database.undeleteresult> undelete(list<id> recordids, boolean allornone, system.accesslevel accesslevel) parameters recordids type: list<id> allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. 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: list<database.undeleteresult> usage undelete is analogous to the undelete statement in sql. each executed undelete method counts against the governor limit for dml statements. 2933apex reference guide database class update(recordtoupdate, allornone) modifies an existing sobject record, such as an individual account or contact, in your organization's data. signature public static database.saveresult update(sobject recordtoupdate, boolean allornone) parameters recordtoupdate type: sobject allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. return value type: database.saveresult usage update is analogous to the update statement in sql. apex classes and triggers saved (compiled) using api version 15.0 and higher produce a runtime error if you assign a string value that is too long for the field. each executed update method counts against the governor limit for dml statements. example the following example updates the billingcity field on a single account. account a = new account(name='sfdc'); insert(a); account myacct = [select id, name, billingcity from account where id = :a.id]; myacct.billingcity = 'san francisco'; database.saveresult sr = database.update(myacct); update(recordstoupdate, allornone) modifies one or more existing sobject records, such as individual accounts or contacts, in your organization’s data. 2934apex reference guide database class signature public static database.saveresult[] update(sobject[] recordstoupdate, boolean allornone) parameters recordstoupdate type: sobject [] allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. return value type: database.save |
result[] usage update is analogous to the update statement in sql. each executed update method counts against the governor limit for dml statements. update(recordtoupdate, dmloptions) modifies an existing sobject record, such as an individual account or contact, in your organization's data. signature public static database.saveresult update(sobject recordtoupdate, database.dmloptions dmloptions) parameters recordtoupdate type: sobject dmloptions type: database.dmloptions the optional dmloptions parameter specifies additional data for the transaction, such as assignment rule information or rollback behavior when errors occur during record insertions. return value type: database.saveresult usage update is analogous to the update statement in sql. 2935apex reference guide database class apex classes and triggers saved (compiled) using api version 15.0 and higher produce a runtime error if you assign a string value that is too long for the field. each executed update method counts against the governor limit for dml statements. update(recordstoupdate, dmloptions) modifies one or more existing sobject records, such as individual accounts or contacts, in your organization’s data. signature public static database.saveresult[] update(sobject[] recordstoupdate, database.dmloptions dmloptions) parameters recordstoupdate type: sobject [] dmloptions type: database.dmloptions the optional dmloptions parameter specifies additional data for the transaction, such as assignment rule information or rollback behavior when errors occur during record insertions. return value type: database.saveresult[] usage update is analogous to the update statement in sql. apex classes and triggers saved (compiled) using api version 15.0 and higher produce a runtime error if you assign a string value that is too long for the field. each executed update method counts against the governor limit for dml statements. update(recordtoupdate, allornone, accesslevel) modifies an existing sobject record, such as an individual account or contact, in your organization's data. signature public static database.saveresult update(sobject recordtoupdate, boolean allornone, system.accesslevel accesslevel) parameters recordtoupdate type: sobject allornone type: boolean 2936apex reference guide database class the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. 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: database.saveresult usage if you use the accesslevel parameter to specify that the method runs in user mode, we report all encountered inaccessible fields. the way to retrieve the names of these inaccessible fields depends on the value of this method's allornone parameter, or the equivalent dmloptions.optallornone property. if you specify that: • allornone=true or dmloptions.optallornone=true: catch the dmlexception and use the dmlexception.getdmlfieldnames() method to retrieve the list of inaccessible fields. see exception class and built-in exceptions for more information. • allornone=false or dmloptions.optallornone=false: for each failing record, we update the database.error object that results from the dml operation. use the error.getfields() method to retrieve the list of inaccessible fields. see the error class methods for more information. update(recordstoupdate, allornone, accesslevel) modifies one or more existing sobject records, such as individual accounts or contacts, in your organization’s data. signature public static list<database.saveresult> update(list<sobject> recordstoupdate, boolean allornone, system.accesslevel accesslevel) parameters recordstoupdate type |
: list<sobject> allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. accesslevel type: system.accesslevel 2937apex reference guide database class (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: list<database.saveresult> usage if you use the accesslevel parameter to specify that the method runs in user mode, we report all encountered inaccessible fields. the way to retrieve the names of these inaccessible fields depends on the value of this method's allornone parameter, or the equivalent dmloptions.optallornone property. if you specify that: • allornone=true or dmloptions.optallornone=true: catch the dmlexception and use the dmlexception.getdmlfieldnames() method to retrieve the list of inaccessible fields. see exception class and built-in exceptions for more information. • allornone=false or dmloptions.optallornone=false: for each failing record, we update the database.error object that results from the dml operation. use the error.getfields() method to retrieve the list of inaccessible fields. see the error class methods for more information. update(recordtoupdate, dmloptions, accesslevel) modifies an existing sobject record, such as an individual account or contact, in your organization's data. signature public static database.saveresult update(sobject recordtoupdate, database.dmloptions dmloptions, system.accesslevel accesslevel) parameters recordtoupdate type: sobject dmloptions type: database.dmloptions the optional dmloptions parameter specifies additional data for the transaction, such as assignment rule information or rollback behavior when errors occur during record insertions. 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: database.saveresult 2938apex reference guide database class update(recordstoupdate, dmloptions, accesslevel) modifies one or more existing sobject records, such as individual accounts or contacts, in your organization’s data. signature public static list<database.saveresult> update(list<sobject> recordstoupdate, database.dmloptions dmloptions, system.accesslevel accesslevel) parameters recordstoupdate type: list<sobject> dmloptions type: database.dmloptions the optional dmloptions parameter specifies additional data for the transaction, such as assignment rule information or rollback behavior when errors occur during record insertions. 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: list<database.saveresult> upsert(recordtoupsert, externalidfield, allornone) creates a new sobject record or updates an existing sobject record within a single statement, using a specified field to determine the presence of existing objects, or the id field if no field is specified. signature public static database.u |
psertresult upsert(sobject recordtoupsert, schema.sobjectfield externalidfield, boolean allornone) parameters recordtoupsert type: sobject externalidfield type: schema.sobjectfield (optional) the externalidfield is of type schema.sobjectfield, that is, a field token. find the token for the field by using the fields special method. for example, schema.sobjectfield f = account.fields.myexternalid. the externalidfield parameter is the field that upsert() uses to match sobjects with existing records. this field can be a custom field marked as external id, or a standard field with the idlookup attribute. 2939apex reference guide database class note: if externalidfield isn’t specified, then the id field is used to determine a match with existing records. allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. return value type: database.upsertresult usage apex classes and triggers saved (compiled) using api version 15.0 and higher produce a runtime error if you assign a string value that is too long for the field. each executed upsert method counts against the governor limit for dml statements. for more information on how the upsert operation works, see the upsert() statement. upsert(recordstoupsert, externalidfield, allornone) creates new sobject records or updates existing sobject records within a single statement, using a specified field to determine the presence of existing objects, or the id field if no field is specified. signature public static database.upsertresult[] upsert(sobject[] recordstoupsert, schema.sobjectfield externalidfield, boolean allornone) parameters recordstoupsert type: sobject [] externalidfield type: schema.sobjectfield (optional) the externalidfield is of type schema.sobjectfield, that is, a field token. find the token for the field by using the fields special method. for example, schema.sobjectfield f = account.fields.myexternalid. the externalidfield parameter is the field that upsert() uses to match sobjects with existing records. this field can be a custom field marked as external id, or a standard field with the idlookup attribute. note: if externalidfield isn’t specified, then the id field is used to determine a match with existing records. allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter isn’t set or is set true, an exception is thrown if the method 2940apex reference guide database class isn’t successful. if the parameter is specified as false and a before-trigger assigns an invalid value to a field, the partial set of valid records isn’t inserted. return value type: database.upsertresult[] usage apex classes and triggers saved (compiled) using api version 15.0 and higher produce a runtime error if you assign a string value that is too long for the field. each executed upsert method counts against the governor limit for dml statements. for more information on how the upsert operation works, see the upsert() statement. upsert(recordtoupsert, externalidfield, allornone, accesslevel) creates a new sobject record or updates an existing sobject record within a single statement, using a specified field to determine the presence of existing objects, or the id field if no field is specified. signature public static database.upsertresult upsert(sobject recordtoupsert, schema.sobjectfield externalidfield, boolean allornone, system.accesslevel accesslevel) parameters recordtoupsert type: sobject externalidfield type: schema.sobjectfield (optional) the externalidfield is of type schema |
.sobjectfield, that is, a field token. find the token for the field by using the fields special method. for example, schema.sobjectfield f = account.fields.myexternalid. the externalidfield parameter is the field that upsert() uses to match sobjects with existing records. this field can be a custom field marked as external id, or a standard field with the idlookup attribute. note: if externalidfield isn’t specified, then the id field is used to determine a match with existing records. allornone type: boolean the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter is not set or is set true, an exception is thrown if the method is not successful. 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 2941apex reference guide database class 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: database.upsertresult usage if you use the accesslevel parameter to specify that the method runs in user mode, we report all encountered inaccessible fields. the way to retrieve the names of these inaccessible fields depends on the value of this method's allornone parameter, or the equivalent dmloptions.optallornone property. if you specify that: • allornone=true or dmloptions.optallornone=true: catch the dmlexception and use the dmlexception.getdmlfieldnames() method to retrieve the list of inaccessible fields. see exception class and built-in exceptions for more information. • allornone=false or dmloptions.optallornone=false: for each failing record, we update the database.error object that results from the dml operation. use the error.getfields() method to retrieve the list of inaccessible fields. see the error class methods for more information. apex classes and triggers saved (compiled) using api version 15.0 and higher produce a runtime error if you assign a string value that is too long for the field. each executed upsert method counts against the governor limit for dml statements. for more information on how the upsert operation works, see the upsert() statement. upsert(recordstoupsert, externalidfield, allornone, accesslevel) creates new sobject records or updates existing sobject records within a single statement, using a specified field to determine the presence of existing objects, or the id field if no field is specified. signature public static list<database.upsertresult> upsert(list<sobject> recordstoupsert, schema.sobjectfield externalidfield, boolean allornone, system.accesslevel accesslevel) parameters recordstoupsert type: list<sobject > externalidfield type: schema.sobjectfield (optional) the externalidfield is of type schema.sobjectfield, that is, a field token. find the token for the field by using the fields special method. for example, schema.sobjectfield f = account.fields.myexternalid. the externalidfield parameter is the field that upsert() uses to match sobjects with existing records. this field can be a custom field marked as external id, or a standard field with the idlookup attribute. note: if externalidfield isn’t specified, then the id field is used to determine a match with existing records. allornone type: boolean 2942apex reference guide database class the optional allornone parameter specifies whether the operation allows partial success. if you specify false for this parameter 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. if the parameter isn’t set or is set true, an exception is thrown if the method isn’t successful. if the parameter is specified as false and a before-trigger assigns an invalid value |
to a field, the partial set of valid records isn’t inserted. 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: list<database.upsertresult> usage if you use the accesslevel parameter to specify that the method runs in user mode, we report all encountered inaccessible fields. the way to retrieve the names of these inaccessible fields depends on the value of this method's allornone parameter, or the equivalent dmloptions.optallornone property. if you specify that: • allornone=true or dmloptions.optallornone=true: catch the dmlexception and use the dmlexception.getdmlfieldnames() method to retrieve the list of inaccessible fields. see exception class and built-in exceptions for more information. • allornone=false or dmloptions.optallornone=false: for each failing record, we update the database.error object that results from the dml operation. use the error.getfields() method to retrieve the list of inaccessible fields. see the error class methods for more information. apex classes and triggers saved (compiled) using api version 15.0 and higher produce a runtime error if you assign a string value that is too long for the field. each executed upsert method counts against the governor limit for dml statements. for more information on how the upsert operation works, see the upsert() statement. updateasync(sobjects, callback) initiates requests to update external object data on the relevant external systems. the requests are executed asynchronously, as background operations, and are sent to the external systems that are defined by the external objects' associated external data sources. allows referencing a callback class whose processsave method is called for each record after the remote operations are completed. signature public static list<database.saveresult> updateasync(list<sobject> sobjects, datasource.asyncsavecallback callback) parameters sobjects type: list<sobject> 2943apex reference guide database class list of external object records to modify. callback type: datasource.asyncsavecallback the callback object that contains the state in the originating context and an action (the processsave method) that executes after the insert operation is completed. use the action callback to update org data according to the operation’s results. the callback object must extend datasource.asyncsavecallback. return value type: list<database.saveresult> status results for the update operation. each result corresponds to a record processed by this asynchronous operation and is associated with a unique identifier (asynclocator). the asynclocator value is included in the errors array of the result. you can retrieve this identifier with database.getasynclocator(). retrieve the final result with database.getasyncsaveresult(). updateasync(sobject, callback) initiates a request to update external object data on the relevant external system. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. allows referencing a callback class whose processsave method is called after the remote operation is completed. signature public static database.saveresult updateasync(sobject sobject, datasource.asyncsavecallback callback) parameters sobject type: sobject external object record to modify. callback type: datasource.asyncsavecallback the callback object that contains the state in the originating context and an action (the processsave method) that executes after the insert operation is completed. use the action callback to update org data according to the operation’s results. the callback object must extend datasource.asyncsavecallback. return value type: database.saveresult status result for the insert operation. the result corresponds to a record processed by this asynchronous operation and is associated with a unique identifier (asynclocator). the asynclocator value is included in the errors array of the result. you can retrieve this identifier with database.getasynclocator(). retrieve the final result with database.getasyncsaveresult(). updateasync(sobjects) initiates |
requests to update external object data on the relevant external systems. the requests are executed asynchronously, as background operations, and are sent to the external systems that are defined by the external objects' associated external data sources. 2944apex reference guide database class signature public static list<database.saveresult> updateasync(list<sobject> sobjects) parameters sobjects type: list<sobject> list of external object records to modify. return value type: list<database.saveresult> status results for the update operation. each result corresponds to a record processed by this asynchronous operation and is associated with a unique identifier (asynclocator). the asynclocator value is included in the errors array of the result. you can retrieve this identifier with database.getasynclocator(). retrieve the final result with database.getasyncsaveresult(). updateasync(sobject) initiates a request to update external object data on the relevant external system. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. signature public static database.saveresult updateasync(sobject sobject) parameters sobject type: sobject external object record to modify. return value type: database.saveresult status result for the insert operation. the result corresponds to a record processed by this asynchronous operation and is associated with a unique identifier (asynclocator). the asynclocator value is included in the errors array of the result. you can retrieve this identifier with database.getasynclocator(). retrieve the final result with database.getasyncsaveresult(). updateasync(sobjects, callback, accesslevel) initiates requests to update external object data on the relevant external systems. the requests are executed asynchronously, as background operations, and are sent to the external systems that are defined by the external objects' associated external data sources. allows referencing a callback class whose processsave method is called for each record after the remote operations are completed. signature public static list<database.saveresult> updateasync(list<sobject> sobjects, datasource.asyncsavecallback callback, system.accesslevel accesslevel) 2945apex reference guide database class parameters sobjects type: list<sobject> list of external object records to modify. callback type: datasource.asyncsavecallback the callback object that contains the state in the originating context and an action (the processsave method) that executes after the insert operation is completed. the execution is in system mode regardless of the accesslevel parameter. use the action callback to update org data according to the operation’s results. the callback object must extend datasource.asyncsavecallback. 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: list<database.saveresult> status results for the update operation. each result corresponds to a record processed by this asynchronous operation and is associated with a unique identifier (asynclocator). the asynclocator value is included in the errors array of the result. you can retrieve this identifier with database.getasynclocator(). retrieve the final result with database.getasyncsaveresult(). updateasync(sobject, callback, accesslevel) initiates a request to update external object data on the relevant external system. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. allows referencing a callback class whose processsave method is called after the remote operation is completed. signature public static database.saveresult updateasync(sobject sobject, datasource.asyncsavecallback callback, system.accesslevel accesslevel) parameters sobject type: sobject external object record to modify. callback type: datasource.asyncsavecallback the callback object that contains the state in the originating context and an action (the processsave method) that executes after the insert operation is completed. the execution is in system mode regardless of the accesslevel parameter. use the action callback to update org data according to the operation’s |
results. the callback object must extend datasource.asyncsavecallback. 2946apex reference guide database class 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: database.saveresult status result for the insert operation. the result corresponds to a record processed by this asynchronous operation and is associated with a unique identifier (asynclocator). the asynclocator value is included in the errors array of the result. you can retrieve this identifier with database.getasynclocator(). retrieve the final result with database.getasyncsaveresult(). updateasync(sobjects, accesslevel) initiates requests to update external object data on the relevant external systems. the requests are executed asynchronously, as background operations, and are sent to the external systems that are defined by the external objects' associated external data sources. signature public static list<database.saveresult> updateasync(list<sobject> sobjects, system.accesslevel accesslevel) parameters sobjects type: list<sobject> list of external object records to modify. 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: list<database.saveresult> status results for the update operation. each result corresponds to a record processed by this asynchronous operation and is associated with a unique identifier (asynclocator). the asynclocator value is included in the errors array of the result. you can retrieve this identifier with database.getasynclocator(). retrieve the final result with database.getasyncsaveresult(). updateasync(sobject, accesslevel) initiates a request to update external object data on the relevant external system. the request is executed asynchronously, as a background operation, and is sent to the external system that's defined by the external object's associated external data source. 2947apex reference guide database class signature public static database.saveresult updateasync(sobject sobject, system.accesslevel accesslevel) parameters sobject type: sobject external object record to modify. 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: database.saveresult status result for the insert operation. the result corresponds to a record processed by this asynchronous operation and is associated with a unique identifier (asynclocator). the asynclocator value is included in the errors array of the result. you can retrieve this identifier with database.getasynclocator(). retrieve the final result with database.getasyncsaveresult(). updateimmediate(sobjects) initiates requests to update external object data on the relevant external systems. the requests are executed synchronously and are sent to the external systems that are defined by the external objects' associated external data sources. if the apex transaction contains pending changes, the synchronous operations can't be completed and throw exceptions. signature public static list<database.saveresult> updateimmediate(list<sobject> sobjects) parameters sobjects type: list<sobject> list of external object records to modify. return value type: list<database.saveresult> status results for the update operation. 2948apex reference guide database class usage the operation allows partial success. if one or more record updates fail, the method doesn’t throw |
an exception and the remainder of the dml operation can still succeed. the returned saveresult objects indicate whether the operation was successful. if it wasn’t successful, the objects also return the error code and description. updateimmediate(sobject) initiates a request to update external object data on the relevant external system. the request is executed synchronously and is sent to the external system that's defined by the external object's associated external data source. if the apex transaction contains pending changes, the synchronous operation can't be completed and throws an exception. signature public static database.saveresult updateimmediate(sobject sobject) parameters sobject type: sobject external object record to modify. return value type: database.saveresult status result for the update operation. usage if a record update fails, the method doesn’t throw an exception. the returned saveresult object indicates whether the operation was successful. if it wasn’t successful, the object returns the error code and description. updateimmediate(sobjects, accesslevel) initiates requests to update external object data on the relevant external systems. the requests are executed synchronously and are sent to the external systems that are defined by the external objects' associated external data sources. if the apex transaction contains pending changes, the synchronous operations can't be completed and throw exceptions. signature public static list<database.saveresult> updateimmediate(list<sobject> sobjects, system.accesslevel accesslevel) parameters sobjects type: list<sobject> list of external object records to modify. accesslevel type: system.accesslevel 2949apex reference guide database class (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: list<database.saveresult> status results for the update operation. usage the operation allows partial success. if one or more record updates fail, the method doesn’t throw an exception and the remainder of the dml operation can still succeed. the returned saveresult objects indicate whether the operation was successful. if it wasn’t successful, the objects also return the error code and description. updateimmediate(sobject, accesslevel) initiates a request to update external object data on the relevant external system. the request is executed synchronously and is sent to the external system that's defined by the external object's associated external data source. if the apex transaction contains pending changes, the synchronous operation can't be completed and throws an exception. signature public static database.saveresult updateimmediate(sobject sobject, system.accesslevel accesslevel) parameters sobject type: sobject external object record to modify. 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: database.saveresult status result for the update operation. usage if a record update fails, the method doesn’t throw an exception. the returned saveresult object indicates whether the operation was successful. if it failed, the object returns the error code and description. 2950apex reference guide date class date class contains methods for the date primitive data type. namespace system usage for more information on dates, see date data type. date methods the following are methods for date. in this section: adddays(additionaldays) adds the specified number of additional days to a date. addmonths(additionalmonths) adds the specified number of additional months to a date addyears(additionalyears) adds the specified number of additional years to a date day() returns the day-of-month component of a date. dayofyear() returns the day-of-year component of a date. daysbetween(seconddate |
) returns the number of days between the date that called the method and the specified date. daysinmonth(year, month) returns the number of days in the month for the specified year and month (1=jan). format() returns the date as a string using the locale of the context user isleapyear(year) returns true if the specified year is a leap year. issameday(datetocompare) returns true if the date that called the method is the same as the specified date. month() returns the month component of a date (1=jan). monthsbetween(seconddate) returns the number of months between the date that called the method and the specified date, ignoring the difference in days. newinstance(year, month, day) constructs a date from integer representations of the year, month (1=jan), and day. 2951apex reference guide date class parse(stringdate) constructs a date from a string. the format of the string depends on the local date format. today() returns the current date in the current user's time zone. tostartofmonth() returns the first of the month for the date that called the method. tostartofweek() returns the start of the week for the date that called the method, depending on the context user's locale. valueof(stringdate) returns a date that contains the value of the specified string. valueof(fieldvalue) converts the specified object to a date. use this method to convert a history tracking field value or an object that represents a date value. year() returns the year component of a date adddays(additionaldays) adds the specified number of additional days to a date. signature public date adddays(integer additionaldays) parameters additionaldays type: integer return value type: date example date mydate = date.newinstance(1960, 2, 17); date newdate = mydate.adddays(2); addmonths(additionalmonths) adds the specified number of additional months to a date signature public date addmonths(integer additionalmonths) 2952apex reference guide date class parameters additionalmonths type: integer return value type: date example date mydate = date.newinstance(1990, 11, 21); date newdate = mydate.addmonths(3); date expecteddate = date.newinstance(1991, 2, 21); system.assertequals(expecteddate, newdate); addyears(additionalyears) adds the specified number of additional years to a date signature public date addyears(integer additionalyears) parameters additionalyears type: integer return value type: date example date mydate = date.newinstance(1983, 7, 15); date newdate = mydate.addyears(2); date expecteddate = date.newinstance(1985, 7, 15); system.assertequals(expecteddate, newdate); day() returns the day-of-month component of a date. signature public integer day() return value type: integer 2953apex reference guide date class example date mydate = date.newinstance(1989, 4, 21); integer day = mydate.day(); system.assertequals(21, day); dayofyear() returns the day-of-year component of a date. signature public integer dayofyear() return value type: integer example date mydate = date.newinstance(1998, 10, 21); integer day = mydate.dayofyear(); system.assertequals(294, day); daysbetween(seconddate) returns the number of days between the date that called the method and the specified date. signature public integer daysbetween(date seconddate) parameters seconddate type: date return value type: integer usage if the date that calls the method occurs after the seconddate, the return value is negative. example date startdate = date.newinstance(2008, 1, 1); date duedate = date.newinstance(2008, 1, 30); integer numberdaysdue = startdate.daysbetween(duedate); 2954apex reference guide date class daysinmonth(year, month) returns the number of days in the month for the specified year and month (1=jan). signature public static integer daysinmonth(integer year, integer month) parameters year type: integer month type: integer return value |
type: integer example the following example finds the number of days in the month of february in the year 1960. integer numberdays = date.daysinmonth(1960, 2); format() returns the date as a string using the locale of the context user signature public string format() return value type: string example // in american-english locale date mydate = date.newinstance(2001, 3, 21); string daystring = mydate.format(); system.assertequals('3/21/2001', daystring); isleapyear(year) returns true if the specified year is a leap year. signature public static boolean isleapyear(integer year) 2955apex reference guide date class parameters year type: integer return value type: boolean example system.assert(date.isleapyear(2004)); issameday(datetocompare) returns true if the date that called the method is the same as the specified date. signature public boolean issameday(date datetocompare) parameters datetocompare type: date return value type: boolean example date mydate = date.today(); date duedate = date.newinstance(2008, 1, 30); boolean duenow = mydate.issameday(duedate); month() returns the month component of a date (1=jan). signature public integer month() return value type: integer 2956apex reference guide date class example date mydate = date.newinstance(2004, 11, 21); integer month = mydate.month(); system.assertequals(11, month); monthsbetween(seconddate) returns the number of months between the date that called the method and the specified date, ignoring the difference in days. signature public integer monthsbetween(date seconddate) parameters seconddate type: date return value type: integer example date firstdate = date.newinstance(2006, 12, 2); date seconddate = date.newinstance(2012, 12, 8); integer monthsbetween = firstdate.monthsbetween(seconddate); system.assertequals(72, monthsbetween); newinstance(year, month, day) constructs a date from integer representations of the year, month (1=jan), and day. signature public static date newinstance(integer year, integer month, integer day) parameters year type: integer month type: integer day type: integer return value type: date 2957apex reference guide date class example the following example creates the date february 17th, 1960: date mydate = date.newinstance(1960, 2, 17); parse(stringdate) constructs a date from a string. the format of the string depends on the local date format. signature public static date parse(string stringdate) parameters stringdate type: string return value type: date example the following example works in some locales. date mydate = date.parse('12/27/2009'); today() returns the current date in the current user's time zone. signature public static date today() return value type: date tostartofmonth() returns the first of the month for the date that called the method. signature public date tostartofmonth() return value type: date 2958apex reference guide date class example date mydate = date.newinstance(1987, 12, 17); date firstdate = mydate.tostartofmonth(); date expecteddate = date.newinstance(1987, 12, 1); system.assertequals(expecteddate, firstdate); tostartofweek() returns the start of the week for the date that called the method, depending on the context user's locale. signature public date tostartofweek() return value type: date example for example, the start of a week is sunday in the united states locale, and monday in european locales. for example: date mydate = date.today(); date weekstart = mydate.tostartofweek(); valueof(stringdate) returns a date that contains the value of the specified string. signature public static date valueof(string stringdate) parameters stringdate type: string return value type: date usage the specified string should use the standard date format “yyyy-mm-dd hh:mm:ss” in the local time zone. example string year |
= '2008'; string month = '10'; 2959apex reference guide date class string day = '5'; string hour = '12'; string minute = '20'; string second = '20'; string stringdate = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second; date mydate = date.valueof(stringdate); valueof(fieldvalue) converts the specified object to a date. use this method to convert a history tracking field value or an object that represents a date value. signature public static date valueof(object fieldvalue) parameters fieldvalue type: object return value type: date usage use this method with the oldvalue or newvalue fields of history sobjects, such as accounthistory, when the field is a date field. example this example converts history tracking fields to date values. list<accounthistory> ahlist = [select field,oldvalue,newvalue from accounthistory]; for(accounthistory ah : ahlist) { system.debug('field: ' + ah.field); if (ah.field == 'mydate__c') { date oldvalue = date.valueof(ah.oldvalue); date newvalue = date.valueof(ah.newvalue); } } versioned behavior changes date.valueof has been versioned in these releases. 2960apex reference guide datetime class api version 33.0 or earlier if you call date.valueof with a datetime object, the method returns a date value that contains the hours, minutes, seconds, and milliseconds set. api version 34.0 to api version 53.0 if you call date.valueof with a datetime object, the method converts datetime to a valid date without the time information, but the result depends on the manner in which the datetime object was initialized. for example, if the datetime object was initialized using datetime.valueof(stringdate), the returned date value contains time (hours) information. if the datetime object is initialized using datetime.newinstance(year, month, day, hour, minute, second) the returned date value doesn’t contain time information. api version 54.0 and later if you call date.valueof with a datetime object, the method converts the object to a valid date without the time information. year() returns the year component of a date signature public integer year() return value type: integer example date mydate = date.newinstance(1988, 12, 17); system.assertequals(1988, mydate.year()); datetime class contains methods for the datetime primitive data type. namespace system usage for more information about the datetime, see datetime data type. datetime methods the following are methods for datetime. 2961apex reference guide datetime class in this section: adddays(additionaldays) adds the specified number of days to a datetime. addhours(additionalhours) adds the specified number of hours to a datetime. addminutes(additionalminutes) adds the specified number of minutes to a datetime. addmonths(additionalmonths) adds the specified number of months to a datetime. addseconds(additionalseconds) adds the specified number of seconds to a datetime. addyears(additionalyears) adds the specified number of years to a datetime. date() returns the date component of a datetime in the local time zone of the context user. dategmt() return the date component of a datetime in the gmt time zone. day() returns the day-of-month component of a datetime in the local time zone of the context user. daygmt() returns the day-of-month component of a datetime in the gmt time zone. dayofyear() returns the day-of-year component of a datetime in the local time zone of the context user. dayofyeargmt() returns the day-of-year component of a datetime in the gmt time zone. format() converts the date to the local time zone and returns the converted date as a formatted string using the locale of the context user. if the time zone cannot be determined, gmt is used. format(dateformatstring) converts the date to the local time zone and returns the converted date as a string using the supplied java simple date format. if the time zone cannot be determined, gmt is used. |
format(dateformatstring, timezone) converts the date to the specified time zone and returns the converted date as a string using the supplied java simple date format. if the supplied time zone is not in the correct format, gmt is used. formatgmt(dateformatstring) returns a datetime as a string using the supplied java simple date format and the gmt time zone. formatlong() converts the date to the local time zone and returns the converted date in long date format. gettime() returns the number of milliseconds since january 1, 1970, 00:00:00 gmt represented by this datetime object. 2962apex reference guide datetime class hour() returns the hour component of a datetime in the local time zone of the context user. hourgmt() returns the hour component of a datetime in the gmt time zone. issameday(datetocompare) returns true if the datetime that called the method is the same as the specified datetime in the local time zone of the context user. millisecond() return the millisecond component of a datetime in the local time zone of the context user. millisecondgmt() return the millisecond component of a datetime in the gmt time zone. minute() returns the minute component of a datetime in the local time zone of the context user. minutegmt() returns the minute component of a datetime in the gmt time zone. month() returns the month component of a datetime in the local time zone of the context user (1=jan). monthgmt() returns the month component of a datetime in the gmt time zone (1=jan). newinstance(milliseconds) constructs a datetime and initializes it to represent the specified number of milliseconds since january 1, 1970, 00:00:00 gmt. newinstance(date, time) constructs a datetime from the specified date and time in the local time zone. newinstance(year, month, day) constructs a datetime from integer representations of the specified year, month (1=jan), and day at midnight in the local time zone. newinstance(year, month, day, hour, minute, second) constructs a datetime from integer representations of the specified year, month (1=jan), day, hour, minute, and second in the local time zone. newinstancegmt(date, time) constructs a datetime from the specified date and time in the gmt time zone. newinstancegmt(year, month, date) constructs a datetime from integer representations of the specified year, month (1=jan), and day at midnight in the gmt time zone newinstancegmt(year, month, date, hour, minute, second) constructs a datetime from integer representations of the specified year, month (1=jan), day, hour, minute, and second in the gmt time zone now() returns the current datetime based on a gmt calendar. parse(datetimestring) constructs a datetime from the given string in the local time zone and in the format of the user locale. second() returns the second component of a datetime in the local time zone of the context user. 2963apex reference guide datetime class secondgmt() returns the second component of a datetime in the gmt time zone. time() returns the time component of a datetime in the local time zone of the context user. timegmt() returns the time component of a datetime in the gmt time zone. valueof(datetimestring) returns a datetime that contains the value of the specified string. valueof(fieldvalue) converts the specified object to a datetime. use this method to convert a history tracking field value or an object that represents a datetime value. valueofgmt(datetimestring) returns a datetime that contains the value of the specified string. year() returns the year component of a datetime in the local time zone of the context user. yeargmt() returns the year component of a datetime in the gmt time zone. adddays(additionaldays) adds the specified number of days to a datetime. signature public datetime adddays(integer additionaldays) parameters additionaldays type: integer return value type: datetime example datetime mydatetime = datetime.newinstance(1960, 2, 17); datetime newdatetime = mydatetime.adddays(2); datetime expected = datetime.newinstance(1960, 2, 19); system.assertequals(expected, new |
datetime); addhours(additionalhours) adds the specified number of hours to a datetime. 2964apex reference guide datetime class signature public datetime addhours(integer additionalhours) parameters additionalhours type: integer return value type: datetime example datetime mydatetime = datetime.newinstance(1997, 1, 31, 7, 8, 16); datetime newdatetime = mydatetime.addhours(3); datetime expected = datetime.newinstance(1997, 1, 31, 10, 8, 16); system.assertequals(expected, newdatetime); addminutes(additionalminutes) adds the specified number of minutes to a datetime. signature public datetime addminutes(integer additionalminutes) parameters additionalminutes type: integer return value type: datetime example datetime mydatetime = datetime.newinstance(1999, 2, 11, 8, 6, 16); datetime newdatetime = mydatetime.addminutes(7); datetime expected = datetime.newinstance(1999, 2, 11, 8, 13, 16); system.assertequals(expected, newdatetime); addmonths(additionalmonths) adds the specified number of months to a datetime. signature public datetime addmonths(integer additionalmonths) 2965apex reference guide datetime class parameters additionalmonths type: integer return value type: datetime example datetime mydatetime = datetime.newinstance(2000, 7, 7, 7, 8, 12); datetime newdatetime = mydatetime.addmonths(1); datetime expected = datetime.newinstance(2000, 8, 7, 7, 8, 12); system.assertequals(expected, newdatetime); addseconds(additionalseconds) adds the specified number of seconds to a datetime. signature public datetime addseconds(integer additionalseconds) parameters additionalseconds type: integer return value type: datetime example datetime mydatetime = datetime.newinstance(2001, 7, 19, 10, 7, 12); datetime newdatetime = mydatetime.addseconds(4); datetime expected = datetime.newinstance(2001, 7, 19, 10, 7, 16); system.assertequals(expected, newdatetime); addyears(additionalyears) adds the specified number of years to a datetime. signature public datetime addyears(integer additionalyears) 2966apex reference guide datetime class parameters additionalyears type: integer return value type: datetime example datetime mydatetime = datetime.newinstance(2009, 12, 17, 13, 6, 6); datetime newdatetime = mydatetime.addyears(1); datetime expected = datetime.newinstance(2010, 12, 17, 13, 6, 6); system.assertequals(expected, newdatetime); date() returns the date component of a datetime in the local time zone of the context user. signature public date date() return value type: date example datetime mydatetime = datetime.newinstance(2006, 3, 16, 12, 6, 13); date mydate = mydatetime.date(); date expected = date.newinstance(2006, 3, 16); system.assertequals(expected, mydate); dategmt() return the date component of a datetime in the gmt time zone. signature public date dategmt() return value type: date example // california local time, pst datetime mydatetime = datetime.newinstance(2006, 3, 16, 23, 0, 0); 2967apex reference guide datetime class date mydate = mydatetime.dategmt(); date expected = date.newinstance(2006, 3, 17); system.assertequals(expected, mydate); day() returns the day-of-month component of a datetime in the local time zone of the context user. signature public integer day() return value type: integer example datetime mydatetime = datetime.newinstance(1986, 2, 21, 23, 0, 0); system.assertequals(21, mydatetime.day()); daygmt() returns the day-of-month component of |
a datetime in the gmt time zone. signature public integer daygmt() return value type: integer example // california local time, pst datetime mydatetime = datetime.newinstance(1987, 1, 14, 23, 0, 3); system.assertequals(15, mydatetime.daygmt()); dayofyear() returns the day-of-year component of a datetime in the local time zone of the context user. signature public integer dayofyear() return value type: integer 2968apex reference guide datetime class example for example, february 5, 2008 08:30:12 would be day 36. datetime mydate = datetime.newinstance(2008, 2, 5, 8, 30, 12); system.assertequals(mydate.dayofyear(), 36); dayofyeargmt() returns the day-of-year component of a datetime in the gmt time zone. signature public integer dayofyeargmt() return value type: integer example // this sample assumes we are in the pst timezone datetime mydatetime = datetime.newinstance(1999, 2, 5, 23, 0, 3); // january has 31 days + 5 days in february = 36 days // dayofyeargmt() adjusts the time zone from the current time zone to gmt // by adding 8 hours to the pst time zone, so it's 37 days and not 36 days system.assertequals(37, mydatetime.dayofyeargmt()); format() converts the date to the local time zone and returns the converted date as a formatted string using the locale of the context user. if the time zone cannot be determined, gmt is used. signature public string format() return value type: string example note: the sample is executed in an org where the “enable icu locale formats” crucial update is enabled. see https://releasenotes.docs.salesforce.com/en-us/spring20/release-notes/rn_forcecom_globalization_enable_icu_cruc.htm. datetime.mydatetime = datetime.newinstance(1993, 6, 6, 3, 3, 3); system.assertequals('6/6/1993, 3:03 am', mydatetime.format()); 2969apex reference guide datetime class format(dateformatstring) converts the date to the local time zone and returns the converted date as a string using the supplied java simple date format. if the time zone cannot be determined, gmt is used. signature public string format(string dateformatstring) parameters dateformatstring type: string return value type: string usage for more information on the java simple date format, see java simpledateformat. example datetime mydt = datetime.newinstance(2022, 5, 4, 19, 37, 55); string mydate = mydt.format('yyyy-mm-dd h:mm a'); string expected = '2022-05-04 7:37 pm'; system.assertequals(expected, mydate); format(dateformatstring, timezone) converts the date to the specified time zone and returns the converted date as a string using the supplied java simple date format. if the supplied time zone is not in the correct format, gmt is used. signature public string format(string dateformatstring, string timezone) parameters dateformatstring type: string timezone type: string valid time zone values for the timezone argument are the time zones of the java timezone class that correspond to the time zones returned by the timezone.getavailableids method in java. we recommend you use full time zone names, not the three-letter abbreviations. 2970apex reference guide datetime class return value type: string usage for more information on the java simple date format, see java simpledateformat. example this example uses format to convert a gmt date to the america/new_york time zone and formats the date using the specified date format. datetime gmtdate = datetime.newinstancegmt(2011,6,1,12,1,5); string strconverteddate = gmtdate.format('mm/dd/yyyy hh:mm:ss', 'america/new_york'); // date is converted to // the new time zone and is adjusted // for daylight saving time. system.assertequals( '06/ |
01/2011 08:01:05', strconverteddate); formatgmt(dateformatstring) returns a datetime as a string using the supplied java simple date format and the gmt time zone. signature public string formatgmt(string dateformatstring) parameters dateformatstring type: string return value type: string usage for more information on the java simple date format, see java simpledateformat. example datetime mydatetime = datetime.newinstance(1993, 6, 6, 3, 3, 3); string formatted = mydatetime.formatgmt('eee, mmm d yyyy hh:mm:ss'); string expected = 'sun, jun 6 1993 10:03:03'; system.assertequals(expected, formatted); 2971apex reference guide datetime class formatlong() converts the date to the local time zone and returns the converted date in long date format. signature public string formatlong() return value type: string example // passing local date based on the pst time zone datetime dt = datetime.newinstance(2012,12,28,10,0,0); // writes 12/28/2012 10:00:00 am pst system.debug('dt.formatlong()=' + dt.formatlong()); gettime() returns the number of milliseconds since january 1, 1970, 00:00:00 gmt represented by this datetime object. signature public long gettime() return value type: long example datetime dt = datetime.newinstance(2007, 6, 23, 3, 3, 3); long gettime = dt.gettime(); long expected = 1182592983000l; system.assertequals(expected, gettime); hour() returns the hour component of a datetime in the local time zone of the context user. signature public integer hour() return value type: integer 2972apex reference guide datetime class example datetime mydatetime = datetime.newinstance(1998, 11, 21, 3, 3, 3); system.assertequals(3 , mydatetime.hour()); hourgmt() returns the hour component of a datetime in the gmt time zone. signature public integer hourgmt() return value type: integer example // california local time datetime mydatetime = datetime.newinstance(2000, 4, 27, 3, 3, 3); system.assertequals(10 , mydatetime.hourgmt()); issameday(datetocompare) returns true if the datetime that called the method is the same as the specified datetime in the local time zone of the context user. signature public boolean issameday(datetime datetocompare) parameters datetocompare type: datetime return value type: boolean example datetime mydate = datetime.now(); datetime duedate = datetime.newinstance(2008, 1, 30); boolean duenow = mydate.issameday(duedate); millisecond() return the millisecond component of a datetime in the local time zone of the context user. 2973apex reference guide datetime class signature public integer millisecond() return value type: integer example datetime mydatetime = datetime.now(); system.debug(mydatetime.millisecond()); millisecondgmt() return the millisecond component of a datetime in the gmt time zone. signature public integer millisecondgmt() return value type: integer example datetime mydatetime = datetime.now(); system.debug(mydatetime.millisecondgmt()); minute() returns the minute component of a datetime in the local time zone of the context user. signature public integer minute() return value type: integer example datetime mydatetime = datetime.newinstance(2001, 2, 27, 3, 3, 3); system.assertequals(3, mydatetime.minute()); minutegmt() returns the minute component of a datetime in the gmt time zone. 2974apex reference guide datetime class signature public integer minutegmt() return value type: integer example datetime mydatetime = datetime.newinstance(2002, 12, 3, 3, 3, 3); system.assertequals(3, mydatetime.minutegmt()); month() returns the month component of a datetime in the |
local time zone of the context user (1=jan). signature public integer month() return value type: integer example datetime mydatetime = datetime.newinstance(2004, 11, 4, 3, 3, 3); system.assertequals(11, mydatetime.month()); monthgmt() returns the month component of a datetime in the gmt time zone (1=jan). signature public integer monthgmt() return value type: integer example datetime mydatetime = datetime.newinstance(2006, 11, 19, 3, 3, 3); system.assertequals(11, mydatetime.monthgmt()); newinstance(milliseconds) constructs a datetime and initializes it to represent the specified number of milliseconds since january 1, 1970, 00:00:00 gmt. 2975apex reference guide datetime class signature public static datetime newinstance(long milliseconds) parameters milliseconds type: long return value type: datetime the returned date is in the gmt time zone. example long longtime = 1341828183000l; datetime dt = datetime.newinstance(longtime); datetime expected = datetime.newinstance(2012, 7, 09, 3, 3, 3); system.assertequals(expected, dt); newinstance(date, time) constructs a datetime from the specified date and time in the local time zone. signature public static datetime newinstance(date date, time time) parameters date type: date time type: time return value type: datetime the returned date is in the gmt time zone. example date mydate = date.newinstance(2011, 11, 18); time mytime = time.newinstance(3, 3, 3, 0); datetime dt = datetime.newinstance(mydate, mytime); datetime expected = datetime.newinstance(2011, 11, 18, 3, 3, 3); system.assertequals(expected, dt); 2976apex reference guide datetime class newinstance(year, month, day) constructs a datetime from integer representations of the specified year, month (1=jan), and day at midnight in the local time zone. signature public static datetime newinstance(integer year, integer month, integer day) parameters year type: integer month type: integer day type: integer return value type: datetime the returned date is in the gmt time zone. example datetime mydate = datetime.newinstance(2008, 12, 1); newinstance(year, month, day, hour, minute, second) constructs a datetime from integer representations of the specified year, month (1=jan), day, hour, minute, and second in the local time zone. signature public static datetime newinstance(integer year, integer month, integer day, integer hour, integer minute, integer second) parameters year type: integer month type: integer day type: integer hour type: integer minute type: integer 2977apex reference guide datetime class second type: integer return value type: datetime the returned date is in the gmt time zone. example datetime mydate = datetime.newinstance(2008, 12, 1, 12, 30, 2); newinstancegmt(date, time) constructs a datetime from the specified date and time in the gmt time zone. signature public static datetime newinstancegmt(date date, time time) parameters date type: date time type: time return value type: datetime example date mydate = date.newinstance(2013, 11, 12); time mytime = time.newinstance(3, 3, 3, 0); datetime dt = datetime.newinstancegmt(mydate, mytime); datetime expected = datetime.newinstancegmt(2013, 11, 12, 3, 3, 3); system.assertequals(expected, dt); newinstancegmt(year, month, date) constructs a datetime from integer representations of the specified year, month (1=jan), and day at midnight in the gmt time zone signature public static datetime newinstancegmt(integer year, integer month, integer date) 2978apex reference guide datetime class parameters year type: integer month type: integer date |
type: integer return value type: datetime example datetime dt = datetime.newinstancegmt(1996, 3, 22); newinstancegmt(year, month, date, hour, minute, second) constructs a datetime from integer representations of the specified year, month (1=jan), day, hour, minute, and second in the gmt time zone signature public static datetime newinstancegmt(integer year, integer month, integer date, integer hour, integer minute, integer second) parameters year type: integer month type: integer date type: integer hour type: integer minute type: integer second type: integer return value type: datetime 2979apex reference guide datetime class example //california local time datetime dt = datetime.newinstancegmt(1998, 1, 29, 2, 2, 3); datetime expected = datetime.newinstance(1998, 1, 28, 18, 2, 3); system.assertequals(expected, dt); now() returns the current datetime based on a gmt calendar. signature public static datetime now() return value type: datetime the format of the returned datetime is: 'mm/dd/yyyy hh:mm period' example datetime mydatetime = datetime.now(); parse(datetimestring) constructs a datetime from the given string in the local time zone and in the format of the user locale. signature public static datetime parse(string datetimestring) parameters datetimestring type: string return value type: datetime the returned date is in the gmt time zone. example this example uses parse to create a datetime from a date passed in as a string and that is formatted for the english (united states) locale. you may need to change the format of the date string if you have a different locale. 2980apex reference guide datetime class note: this sample is executed in an org where the “enable icu locale formats” crucial update is enabled. see https://releasenotes.docs.salesforce.com/en-us/spring20/release-notes/rn_forcecom_globalization_enable_icu_cruc.htm. datetime dt = datetime.parse('10/14/2011, 11:46 am'); string mydtstring = dt.format(); system.assertequals(mydtstring, '10/14/2011, 11:46 am'); second() returns the second component of a datetime in the local time zone of the context user. signature public integer second() return value type: integer example datetime dt = datetime.newinstancegmt(1999, 9, 22, 3, 1, 2); system.assertequals(2, dt.second()); secondgmt() returns the second component of a datetime in the gmt time zone. signature public integer secondgmt() return value type: integer example datetime dt = datetime.newinstance(2000, 2, 3, 3, 1, 5); system.assertequals(5, dt.secondgmt()); time() returns the time component of a datetime in the local time zone of the context user. signature public time time() 2981apex reference guide datetime class return value type: time example datetime dt = datetime.newinstance(2002, 11, 21, 0, 2, 2); time expected = time.newinstance(0, 2, 2, 0); system.assertequals(expected, dt.time()); timegmt() returns the time component of a datetime in the gmt time zone. signature public time timegmt() return value type: time example // this sample is based on the pst time zone datetime dt = datetime.newinstance(2004, 1, 27, 4, 1, 2); time expected = time.newinstance(12, 1, 2, 0); // 8 hours are added to the time to convert it from // pst to gmt system.assertequals(expected, dt.timegmt()); valueof(datetimestring) returns a datetime that contains the value of the specified string. signature public static datetime valueof(string datetimestring) parameters datetimestring type: string return value type: datetime |
the returned date is in the gmt time zone. 2982 |
apex reference guide datetime class usage the specified string should use the standard date format “yyyy-mm-dd hh:mm:ss” in the local time zone. example string year = '2008'; string month = '10'; string day = '5'; string hour = '12'; string minute = '20'; string second = '20'; string stringdate = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second; datetime mydate = datetime.valueof(stringdate); valueof(fieldvalue) converts the specified object to a datetime. use this method to convert a history tracking field value or an object that represents a datetime value. signature public static datetime valueof(object fieldvalue) parameters fieldvalue type: object return value type: datetime usage use this method with the oldvalue or newvalue fields of history sobjects, such as accounthistory, when the field is a date/time field. example list<accounthistory> ahlist = [select field,oldvalue,newvalue from accounthistory]; for(accounthistory ah : ahlist) { system.debug('field: ' + ah.field); if (ah.field == 'mydatetime__c') { datetime oldvalue = datetime.valueof(ah.oldvalue); datetime newvalue = datetime.valueof(ah.newvalue); } } 2983apex reference guide datetime class valueofgmt(datetimestring) returns a datetime that contains the value of the specified string. signature public static datetime valueofgmt(string datetimestring) parameters datetimestring type: string return value type: datetime usage the specified string should use the standard date format “yyyy-mm-dd hh:mm:ss” in the gmt time zone. example // california locale time string year = '2009'; string month = '3'; string day = '5'; string hour = '5'; string minute = '2'; string second = '2'; string stringdate = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second; datetime mydate = datetime.valueofgmt(stringdate); datetime expected = datetime.newinstance(2009, 3, 4, 21, 2, 2); system.assertequals(expected, mydate); year() returns the year component of a datetime in the local time zone of the context user. signature public integer year() return value type: integer 2984apex reference guide decimal class example datetime dt = datetime.newinstance(2012, 1, 26, 5, 2, 4); system.assertequals(2012, dt.year()); yeargmt() returns the year component of a datetime in the gmt time zone. signature public integer yeargmt() return value type: integer example datetime dt = datetime.newinstance(2012, 10, 4, 6, 4, 6); system.assertequals(2012, dt.yeargmt()); decimal class contains methods for the decimal primitive data type. namespace system usage note: two decimal objects that are numerically equivalent but differ in scale (such as 1.1 and 1.10) generally do not have the same hashcode. use caution when such decimal objects are used in sets or as map keys. for more information on decimal, see decimal data type. in this section: rounding mode rounding mode specifies the rounding behavior for numerical operations capable of discarding precision. decimal methods rounding mode rounding mode specifies the rounding behavior for numerical operations capable of discarding precision. each rounding mode indicates how the least significant returned digit of a rounded result is to be calculated. the following are the valid values for roundingmode. 2985apex reference guide decimal class name description ceiling rounds towards positive infinity. that is, if the result is positive, this mode behaves the same as the up rounding mode; if the result is negative, it behaves the same as the down rounding mode. note that this rounding mode never decreases the calculated value. for example: • input number 5.5: ceiling round mode result: 6 • input number 1.1: ceiling round mode result: 2 • input number |
-1.1: ceiling round mode result: -1 • input number -2.7: ceiling round mode result: -2 decimal[] example = new decimal[]{5.5, 1.1, -1.1, -2.7}; long[] expected = new long[]{6, 2, -1, -2}; for(integer x = 0; x < example.size(); x++){ system.assertequals(expected[x], example[x].round(system.roundingmode.ceiling)); } down rounds towards zero. this rounding mode always discards any fractions (decimal points) prior to executing. note that this rounding mode never increases the magnitude of the calculated value. for example: • input number 5.5: down round mode result: 5 • input number 1.1: down round mode result: 1 • input number -1.1: down round mode result: -1 • input number -2.7: down round mode result: -2 decimal[] example = new decimal[]{5.5, 1.1, -1.1, -2.7}; long[] expected = new long[]{5, 1, -1, -2}; for(integer x = 0; x < example.size(); x++){ system.assertequals(expected[x], example[x].round(system.roundingmode.down)); } floor rounds towards negative infinity. that is, if the result is positive, this mode behaves the same as thedown rounding mode; if negative, this mode behaves the same as the up rounding mode. note that this rounding mode never increases the calculated value. for example: • input number 5.5: floor round mode result: 5 • input number 1.1: floor round mode result: 1 • input number -1.1: floor round mode result: -2 • input number -2.7: floor round mode result: -3 decimal[] example = new decimal[]{5.5, 1.1, -1.1, -2.7}; long[] expected = new long[]{5, 1, -2, -3}; for(integer x = 0; x < example.size(); x++){ system.assertequals(expected[x], example[x].round(system.roundingmode.floor)); } 2986apex reference guide decimal class name description half_down rounds towards the “nearest neighbor” unless both neighbors are equidistant, in which case this mode rounds down. this rounding mode behaves the same as the up rounding mode if the discarded fraction (decimal point) is > 0.5; otherwise, it behaves the same as down rounding mode. for example: • input number 5.5: half_down round mode result: 5 • input number 1.1: half_down round mode result: 1 • input number -1.1: half_down round mode result: -1 • input number -2.7: half_down round mode result: -3 decimal[] example = new decimal[]{5.5, 1.1, -1.1, -2.7}; long[] expected = new long[]{5, 1, -1, -3}; for(integer x = 0; x < example.size(); x++){ system.assertequals(expected[x], example[x].round(system.roundingmode.half_down)); } half_even rounds towards the “nearest neighbor” unless both neighbors are equidistant, in which case, this mode rounds towards the even neighbor. this rounding mode behaves the same as the half_up rounding mode if the digit to the left of the discarded fraction (decimal point) is odd. it behaves the same as the half_down rounding method if it is even. for example: • input number 5.5: half_even round mode result: 6 • input number 1.1: half_even round mode result: 1 • input number -1.1: half_even round mode result: -1 • input number -2.7: half_even round mode result: -3 decimal[] example = new decimal[]{5.5, 1.1, -1.1, -2.7}; long[] expected = new long[]{6, 1, -1, -3}; for(integer x = |
0; x < example.size(); x++){ system.assertequals(expected[x], example[x].round(system.roundingmode.half_even)); } note that this rounding mode statistically minimizes cumulative error when applied repeatedly over a sequence of calculations. half_up rounds towards the “nearest neighbor” unless both neighbors are equidistant, in which case, this mode rounds up. this rounding method behaves the same as the up rounding method if the discarded fraction (decimal point) is >= 0.5; otherwise, this rounding method behaves the same as the down rounding method. for example: • input number 5.5: half_up round mode result: 6 • input number 1.1: half_up round mode result: 1 • input number -1.1: half_up round mode result: -1 • input number -2.7: half_up round mode result: -3 decimal[] example = new decimal[]{5.5, 1.1, -1.1, -2.7}; long[] expected = new long[]{6, 1, -1, -3}; for(integer x = 0; x < example.size(); x++){ 2987apex reference guide decimal class name description system.assertequals(expected[x], example[x].round(system.roundingmode.half_up)); } unnecessary asserts that the requested operation has an exact result, which means that no rounding is necessary. if this rounding mode is specified on an operation that yields an inexact result, a mathexception is thrown. for example: • input number 5.5: unnecessary round mode result: mathexception • input number 1.1: unnecessary round mode result: mathexception • input number 1.0: unnecessary round mode result: 1 • input number -1.0: unnecessary round mode result: -1 • input number -2.2: unnecessary round mode result: mathexception decimal example1 = 5.5; decimal example2 = 1.0; system.assertequals(1, example2.round(system.roundingmode.unnecessary)); try{ example1.round(system.roundingmode.unnecessary); } catch(exception e) { system.assertequals('system.mathexception', e.gettypename()); } up rounds away from zero. this rounding mode always truncates any fractions (decimal points) prior to executing. note that this rounding mode never decreases the magnitude of the calculated value. for example: • input number 5.5: up round mode result: 6 • input number 1.1: up round mode result: 2 • input number -1.1: up round mode result: -2 • input number -2.7: up round mode result: -3 decimal[] example = new decimal[]{5.5, 1.1, -1.1, -2.7}; long[] expected = new long[]{6, 2, -2, -3}; for(integer x = 0; x < example.size(); x++){ system.assertequals(expected[x], example[x].round(system.roundingmode.up)); } decimal methods the following are methods for decimal. in this section: abs() returns the absolute value of the decimal. 2988apex reference guide decimal class divide(divisor, scale) divides this decimal by the specified divisor, and sets the scale, that is, the number of decimal places, of the result using the specified scale. divide(divisor, scale, roundingmode) divides this decimal by the specified divisor, sets the scale, that is, the number of decimal places, of the result using the specified scale, and if necessary, rounds the value using the rounding mode. doublevalue() returns the double value of this decimal. format() returns the string value of this decimal using the locale of the context user. intvalue() returns the integer value of this decimal. longvalue() returns the long value of this decimal. pow(exponent) returns the value of this decimal raised to the power of the specified exponent. precision() returns the total number of digits for the decimal. round() 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. round(roundingmode) returns the rounded approximation of this decimal. the number is rounded to zero decimal places using the rounding mode specified by the rounding mode. scale() returns the scale of the decimal, that is, the number of decimal places. setscale(scale) returns the decimal scaled to the specified number of decimal places, using half-even rounding, if necessary. half-even rounding mode rounds toward the “nearest neighbor.” if both neighbors are equidistant, the number is rounded toward the even neighbor. setscale(scale, roundingmode) returns the decimal scaled to the specified number of decimal places, using the specified rounding mode, if necessary. striptrailingzeros() returns the decimal with any trailing zeros removed. toplainstring() returns the string value of this decimal, without using scientific notation. valueof(doubletodecimal) returns a decimal that contains the value of the specified double. valueof(longtodecimal) returns a decimal that contains the value of the specified long. 2989apex reference guide decimal class valueof(stringtodecimal) returns a decimal that contains the value of the specified string. as in java, the string is interpreted as representing a signed decimal. abs() returns the absolute value of the decimal. signature public decimal abs() return value type: decimal example decimal mydecimal = -6.02214129; system.assertequals(6.02214129, mydecimal.abs()); divide(divisor, scale) divides this decimal by the specified divisor, and sets the scale, that is, the number of decimal places, of the result using the specified scale. signature public decimal divide(decimal divisor, integer scale) parameters divisor type: decimal scale type: integer return value type: decimal example decimal decimalnumber = 19; decimal result = decimalnumber.divide(100, 3); system.assertequals(0.190, result); divide(divisor, scale, roundingmode) divides this decimal by the specified divisor, sets the scale, that is, the number of decimal places, of the result using the specified scale, and if necessary, rounds the value using the rounding mode. 2990apex reference guide decimal class signature public decimal divide(decimal divisor, integer scale, system.roundingmode roundingmode) parameters divisor type: decimal scale type: integer roundingmode type: system.roundingmode return value type: decimal example decimal mydecimal = 12.4567; decimal divdec = mydecimal.divide(7, 2, system.roundingmode.up); system.assertequals(divdec, 1.78); doublevalue() returns the double value of this decimal. signature public double doublevalue() return value type: double example decimal mydecimal = 6.62606957; double value = mydecimal.doublevalue(); system.assertequals(6.62606957, value); format() returns the string value of this decimal using the locale of the context user. signature public string format() 2991apex reference guide decimal class return value type: string usage scientific notation will be used if an exponent is needed. example // u.s. locale decimal mydecimal = 12345.6789; system.assertequals('12,345.679', mydecimal.format()); intvalue() returns the integer value of this decimal. signature public integer intvalue() return value type: integer example decimal mydecimal = 1.602176565; system.assertequals(1, mydecimal.intvalue()); longvalue() returns the long value of this decimal. signature public long longvalue() return value type: long example decimal mydecimal = 376.730313461; system.assertequals(376, mydecimal.longvalue()); pow(exponent |
) returns the value of this decimal raised to the power of the specified exponent. 2992apex reference guide decimal class signature public decimal pow(integer exponent) parameters exponent type: integer the value of exponent must be between 0 and 32,767. return value type: decimal usage if you use mydecimal.pow(0), 1 is returned. the math.pow method does accept negative values. example decimal mydecimal = 4.12; decimal powdec = mydecimal.pow(2); system.assertequals(powdec, 16.9744); precision() returns the total number of digits for the decimal. signature public integer precision() return value type: integer example for example, if the decimal value was 123.45, precision returns 5. if the decimal value is 123.123, precision returns 6. decimal d1 = 123.45; integer precision1 = d1.precision(); system.assertequals(precision1, 5); decimal d2 = 123.123; integer precision2 = d2.precision(); system.assertequals(precision2, 6); 2993apex reference guide decimal class round() 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 long round() return value type: long usage note that this rounding mode statistically minimizes cumulative error when applied repeatedly over a sequence of calculations. example decimal d = 4.5; long l = d.round(); system.assertequals(4, l); decimal d1 = 5.5; long l1 = d1.round(); system.assertequals(6, l1); decimal d2 = 5.2; long l2 = d2.round(); system.assertequals(5, l2); decimal d3 = -5.7; long l3 = d3.round(); system.assertequals(-6, l3); round(roundingmode) returns the rounded approximation of this decimal. the number is rounded to zero decimal places using the rounding mode specified by the rounding mode. signature public long round(system.roundingmode roundingmode) parameters roundingmode type: system.roundingmode 2994apex reference guide decimal class return value type: long scale() returns the scale of the decimal, that is, the number of decimal places. signature public integer scale() return value type: integer example decimal mydecimal = 9.27400968; system.assertequals(8, mydecimal.scale()); setscale(scale) returns the decimal scaled to the specified number of decimal places, using half-even rounding, if necessary. half-even rounding mode rounds toward the “nearest neighbor.” if both neighbors are equidistant, the number is rounded toward the even neighbor. signature public decimal setscale(integer scale) parameters scale type: integer the value of scale must be between –33 and 33. if the value of scale is negative, your unscaled value is multiplied by 10 to the power of the negation of scale. for example, after this operation, the value of d is 4*10^3. decimal d = 4000; d = d.setscale(-3); return value type: decimal usage if you do not explicitly set the scale for a decimal, the item from which the decimal is created determines the scale. • if the decimal is created as part of a query, the scale is based on the scale of the field returned from the query. • if the decimal is created from a string, the scale is the number of characters after the decimal point of the string. 2995apex reference guide decimal class • if the decimal is created from a non-decimal number, the number is first converted to a string. scale is then set using the number of characters after the decimal point. example decimal mydecimal = 8.987551787; decimal setscaled = mydecimal.setscale(3); system.assertequals(8.988, setscaled); setscale(scale, roundingmode |
) returns the decimal scaled to the specified number of decimal places, using the specified rounding mode, if necessary. signature public decimal setscale(integer scale, system.roundingmode roundingmode) parameters scale type: integer the value of scale must be between –33 and 33. if the value of scale is negative, your unscaled value is multiplied by 10 to the power of the negation of scale. for example, after this operation, the value of d is 4*10^3. decimal d = 4000; d = d.setscale(-3); roundingmode type: system.roundingmode return value type: decimal usage if you do not explicitly set the scale for a decimal, the item from which the decimal is created determines the scale. • if the decimal is created as part of a query, the scale is based on the scale of the field returned from the query. • if the decimal is created from a string, the scale is the number of characters after the decimal point of the string. • if the decimal is created from a non-decimal number, the number is first converted to a string. scale is then set using the number of characters after the decimal point. striptrailingzeros() returns the decimal with any trailing zeros removed. signature public decimal striptrailingzeros() 2996apex reference guide decimal class return value type: decimal example decimal mydecimal = 1.10000; decimal stripped = mydecimal.striptrailingzeros(); system.assertequals(stripped, 1.1); toplainstring() returns the string value of this decimal, without using scientific notation. signature public string toplainstring() return value type: string example decimal mydecimal = 12345.6789; system.assertequals('12345.6789', mydecimal.toplainstring()); valueof(doubletodecimal) returns a decimal that contains the value of the specified double. signature public static decimal valueof(double doubletodecimal) parameters doubletodecimal type: double return value type: decimal example double mydouble = 2.718281828459045; decimal mydecimal = decimal.valueof(mydouble); system.assertequals(2.718281828459045, mydecimal); 2997apex reference guide domain class valueof(longtodecimal) returns a decimal that contains the value of the specified long. signature public static decimal valueof(long longtodecimal) parameters longtodecimal type: long return value type: decimal example long mylong = 299792458; decimal mydecimal = decimal.valueof(mylong); system.assertequals(299792458, mydecimal); valueof(stringtodecimal) returns a decimal that contains the value of the specified string. as in java, the string is interpreted as representing a signed decimal. signature public static decimal valueof(string stringtodecimal) parameters stringtodecimal type: string return value type: decimal example string temp = '12.4567'; decimal mydecimal = decimal.valueof(temp); domain class represents an existing domain hosted by salesforce that serves the org or its content. contains methods to obtain information about these domains, such as the domain type, my domain name, and sandbox name. 2998apex reference guide domain class namespace system usage use the domain class to obtain information about the domains that salesforce hosts for your org. this class only applies to domains hosted by salesforce, and can’t be used to generate a new domain. example this code uses the system.domainparser class to parse a hostname. it then gets the associated domain type. system.domain d = domainparser.parse('mycompany.lightning.force.com'); string mydomainname = d.getmydomainname(); system.domaintype domaintype = d.getdomaintype(); in this section: domain methods domain methods the following are methods for domain. in this section: getdomaintype() returns the domain’s type, such as content_domain, experience_cloud_sites_domain, or lightning_domain. getmydomainname() returns |
the domain’s my domain name. getpackagename() for a domain that includes the package name, such as a lightning component domain or visualforce page domain, returns the package name. for a domain that doesn’t contain a package name, this method returns null. getsandboxname() for a sandbox org domain, returns the sandbox name. for a production org domain, returns null. getsitessubdomainname() for a system-managed experience cloud site domain or salesforce site domain, returns the sites subdomain name. if enhanced domains are enabled, this method always returns null. when enhanced domains are enabled, the org’s my domain name is the subdomain for the system-managed domains for experience cloud sites and salesforce sites domains. getdomaintype() returns the domain’s type, such as content_domain, experience_cloud_sites_domain, or lightning_domain. signature public system.domaintype getdomaintype() 2999apex reference guide domain class return value type: system.domaintype getmydomainname() returns the domain’s my domain name. signature public string getmydomainname() return value type: string getpackagename() for a domain that includes the package name, such as a lightning component domain or visualforce page domain, returns the package name. for a domain that doesn’t contain a package name, this method returns null. signature public string getpackagename() return value type: string getsandboxname() for a sandbox org domain, returns the sandbox name. for a production org domain, returns null. signature public string getsandboxname() return value type: string getsitessubdomainname() for a system-managed experience cloud site domain or salesforce site domain, returns the sites subdomain name. if enhanced domains are enabled, this method always returns null. when enhanced domains are enabled, the org’s my domain name is the subdomain for the system-managed domains for experience cloud sites and salesforce sites domains. signature public string getsitessubdomainname() 3000apex reference guide domaincreator class return value type: string domaincreator class use the domaincreator class to return a hostname specific to the org. for example, get the org’s visualforce hostname. values are returned as a hostname, such as mydomainname.lightning.force.com. namespace system examples this example code fetches the org’s my domain login hostname and the visualforce hostname for the uat package. //get the my domain login hostname string mydomainhostname = domaincreator.getorgmydomainhostname(); //get the visualforce hostname string vfhostname = domaincreator.getvisualforcehostname('uat'); in this case, in a production org with a my domain name of mycompany, mydomainhostname returns mycompany.my.salesforce.com. and in the same production org with enhanced domains, vfhostname returns mycompany--uat.vf.force.com. this example code creates a link to a salesforce account record. it gets the lightning hostname associated with this org. it then gets the account record id and uses concatenation to build the link url. //get the org’s lightning hostname string mylightninghostname = domaincreator.getlightninghostname(); //get the id of a record account with the name ‘acme’ account acct = [select id from account where name = 'acme' limit 1]; //build the url to view the account record string fullrecordurl = 'https://' + mylightninghostname + '/lightning/r/account/' + acct.id + '/view'; in this section: domaincreator methods domaincreator methods the following are methods for domaincreator. in this section: getcontenthostname() returns the hostname for content stored in the org, such as files. 3001apex reference guide domaincreator class getexperiencecloudsitesbuilderhostname() returns the hostname to access experience builder for the org’s experience cloud sites. getexperiencecloudsiteshostname() returns the system-managed hostname for the org’s experience cloud sites, such as experiencecloudsitessubdomainname.force.com. if digital experiences aren’t enabled, this method throws an invalidparametervalue |
exception. getexperiencecloudsiteslivepreviewhostname() returns the hostname to access experience builder live preview for the org’s experience cloud sites. getexperiencecloudsitespreviewhostname() returns the hostname to access experience builder preview for the org’s experience cloud sites. getlightningcontainercomponenthostname(packagename) returns the hostname for the org’s lightning container components. getlightninghostname() returns the hostname for the org’s lightning pages. getorgmydomainhostname() returns the hostname for the org’s my domain login domain. getsalesforcesiteshostname() returns the hostname for the org’s salesforce sites. if salesforce sites aren’t enabled, this method throws an invalidparametervalueexception. getvisualforcehostname(packagename) returns the hostname for the org’s visualforce pages. getcontenthostname() returns the hostname for content stored in the org, such as files. signature public static string getcontenthostname() return value type: string getexperiencecloudsitesbuilderhostname() returns the hostname to access experience builder for the org’s experience cloud sites. signature public static string getexperiencecloudsitesbuilderhostname() return value type: string 3002apex reference guide domaincreator class getexperiencecloudsiteshostname() returns the system-managed hostname for the org’s experience cloud sites, such as experiencecloudsitessubdomainname.force.com. if digital experiences aren’t enabled, this method throws an invalidparametervalueexception. signature public static string getexperiencecloudsiteshostname() return value type: string getexperiencecloudsiteslivepreviewhostname() returns the hostname to access experience builder live preview for the org’s experience cloud sites. signature public static string getexperiencecloudsiteslivepreviewhostname() return value type: string getexperiencecloudsitespreviewhostname() returns the hostname to access experience builder preview for the org’s experience cloud sites. signature public static string getexperiencecloudsitespreviewhostname() return value type: string getlightningcontainercomponenthostname(packagename) returns the hostname for the org’s lightning container components. signature public static string getlightningcontainercomponenthostname(string packagename) parameters packagename type: string the package name for this component. 3003apex reference guide domaincreator class if packagename is null, this method uses the org’s namespace prefix as the package name. otherwise, it uses the default namespace. return value type: string getlightninghostname() returns the hostname for the org’s lightning pages. signature public static string getlightninghostname() return value type: string getorgmydomainhostname() returns the hostname for the org’s my domain login domain. signature public static string getorgmydomainhostname() return value type: string getsalesforcesiteshostname() returns the hostname for the org’s salesforce sites. if salesforce sites aren’t enabled, this method throws an invalidparametervalueexception. signature public static string getsalesforcesiteshostname() return value type: string getvisualforcehostname(packagename) returns the hostname for the org’s visualforce pages. signature public static string getvisualforcehostname(string packagename) 3004apex reference guide domainparser class parameters packagename type: string the package name for this component. if packagename is null, this method uses the org’s namespace prefix as the package name. otherwise, it uses the default namespace. return value type: string domainparser class use the domainparser class to parse a domain that salesforce hosts for the org and extract information about the domain. namespace system examples this example code parses the org’s lightning domain and gets the my domain name and domain type from the system.domain object. system.domain d = domainparser.parser('mycompany.lightning.force.com'); string mydomainname = d.getmydomainname(); system.domaintype domaintype = d.getdomaintype(); this example code parses a known visualforce url to get the domain type, the org’s my domain name, and the package name. //parse a known url system |
.domain domain = domainparser.parse('https://mycompany--abcpackage.vf.force.com'); //get the domain type system.domaintype domaintype = domain.getdomaintype(); // returns visualforce_domain //get the org’s my domain name string mydomainname = domain.getmydomainname(); // returns mycompany //get the package name string packagename = domain.getpackagename(); // returns abcpackage in this section: domainparser methods domainparser methods the following are methods for domainparser. 3005apex reference guide domainparser class in this section: parse(hostname) parses a passed hostname of a domain that salesforce hosts for the org, and returns the system.domain. parse(url) parses a passed uniform resource locator (url) of a domain that salesforce hosts for the org, and returns the system.domain. parse(hostname) parses a passed hostname of a domain that salesforce hosts for the org, and returns the system.domain. signature public static system.domain parse(string hostname) parameters hostname type: string the label that identifies a salesforce host, including all subdomains but without the protocol, path, or any parameters. for example, mycompany.my.site.com or mycompany--sandbox1.sandbox.my.salesforceforce.com. if the hostname format is invalid, it isn’t a salesforce hosted domain, or it isn’t owned by this org, this method throws an invalidparametervalueexception. return value type: system.domain parse(url) parses a passed uniform resource locator (url) of a domain that salesforce hosts for the org, and returns the system.domain. signature public static system.domain parse(system.url url) parameters url type: system.url a uniform resource locator (url) for a salesforce org, including all subdomains and the protocol. for example, https://mycompany--sandbox1.sandbox.my.salesforceforce.com. the url can also include paths and parameters. for example, https://mycompany.my.site.com/en/us/help or https://mycompany.file.force.com/servlet/servlet.filedownload?file=015300000000xvu. if the url format is invalid, it isn’t a salesforce hosted domain, or it isn’t owned by this org, this method throws an invalidparametervalueexception. 3006apex reference guide domaintype enum return value type: system.domain domaintype enum specifies the domain type for a system.domain. usage use the domaintype enum to obtain the type of a domain parsed through the system.domainparser class. enum values the following are the values of the system.domaintype enum. these values only apply to salesforce-hosted domains. value description cms_domain content management system (cms) public channel domains. content_domain domains that serve content (files) stored in salesforce. customer_360_admin_domain customer 360 data manager domains. customer_360_domain customer 360 data manager admin domains. experience_cloud_sites_builder_domain experience builder for experience cloud sites domains. experience_cloud_sites_domain salesforce-hosted domains that serve experience cloud sites. experience_cloud_sites_live_preview_domain experience builder live preview domains. experience_cloud_sites_preview_domain experience builder preview domains. lightning_container_component_domain lightning container component domains. lightning_domain domains that serve lighting pages. org_my_domain my domain login domains. salesforce_sites_domain salesforce-hosted domains that serve salesforce sites. visualforce_domain domains that serve visualforce pages. double class contains methods for the double primitive data type. namespace system 3007apex reference guide double class usage for more information on double, see double data type. double methods the following are methods for double. in this section: format() returns the string value for this double using the locale of the context user intvalue() returns |
the integer value of this double by casting it to an integer. longvalue() returns the long value of this double. round() returns the closest long to this double value. valueof(stringtodouble) returns a double that contains the value of the specified string. as in java, the string is interpreted as representing a signed decimal. valueof(fieldvalue) converts the specified object to a double value. use this method to convert a history tracking field value or an object that represents a double value. format() returns the string value for this double using the locale of the context user signature public string format() return value type: string example double mydouble = 1261992; system.assertequals('1,261,992', mydouble.format()); intvalue() returns the integer value of this double by casting it to an integer. signature public integer intvalue() 3008apex reference guide double class return value type: integer example double dd1 = double.valueof('3.14159'); integer value = dd1.intvalue(); system.assertequals(value, 3); longvalue() returns the long value of this double. signature public long longvalue() return value type: long example double mydouble = 421994; long value = mydouble.longvalue(); system.assertequals(421994, value); round() returns the closest long to this double value. signature public long round() return value type: long example double d1 = 4.5; long l1 = d1.round(); system.assertequals(5, l1); double d2= 4.2; long l2= d2.round(); system.assertequals(4, l2); double d3= -4.7; 3009apex reference guide double class long l3= d3.round(); system.assertequals(-5, l3); valueof(stringtodouble) returns a double that contains the value of the specified string. as in java, the string is interpreted as representing a signed decimal. signature public static double valueof(string stringtodouble) parameters stringtodouble type: string return value type: double example double dd1 = double.valueof('3.14159'); valueof(fieldvalue) converts the specified object to a double value. use this method to convert a history tracking field value or an object that represents a double value. signature public static double valueof(object fieldvalue) parameters fieldvalue type: object return value type: double usage use this method with the oldvalue or newvalue fields of history sobjects, such as accounthistory, when the field type corresponds to a double type, like a number field. 3010apex reference guide emailmessages class example list<accounthistory> ahlist = [select field,oldvalue,newvalue from accounthistory]; for(accounthistory ah : ahlist) { system.debug('field: ' + ah.field); if (ah.field == 'numberofemployees') { double oldvalue = double.valueof(ah.oldvalue); double newvalue = double.valueof(ah.newvalue); } emailmessages class use the methods in the emailmessages class to interact with emails and email threading. namespace system emailmessages methods the following are static methods for emailmessages. in this section: getformattedthreadingtoken(recordid) returns an email threading token that’s formatted with the correct prefix and suffix. this token can be embedded in an outbound email body, email subject, or both the body and subject. when users reply to the email, threading tokens can be used to attach responses to a record, such as a case record in email-to-case. getrecordidfromemail(subject, textbody, htmlbody) returns the record id corresponding to the specified email threading token, or returns null if none is found. getformattedthreadingtoken(recordid) returns an email threading token that’s formatted with the correct prefix and suffix. this token can be embedded in an outbound email body, email subject, or both the body and subject. when users reply to the email, threading tokens can be used to attach responses to a record, such as a case record in email-to-case. signature public static id getformatted |
threadingtoken(id recordid) parameters recordid type:id 3011apex reference guide emailmessages class the record id associated with the threading token. only case record ids are supported. return value type: string the returned value is a formatted string that includes a prefix and suffix, for example: thread::pp5xpgfmnf2hrzdrcwnrohc:: usage requires lightning threading to be enabled in email-to-case. when sending emails in apex, use the returned string to match emails to a record, such as a case record, that’s associated with the email thread. embed the formatted token in the body or subject of outgoing emails. to find the corresponding record id in incoming emails, use emailmessages.getrecordidfromemail(subject, textbody, htmlbody) on page 3012. example in this sample, we send an email with a threading token so that the email and any responses are associated with the related case. // get your record id. here, we're using a dummy case id. id caseid = id.valueof('500xx000000bpktaaq'); // get the formatted threading token. string formattedtoken = emailmessages.getformattedthreadingtoken(caseid); // create a singleemailmessage object. messaging.singleemailmessage email = new messaging.singleemailmessage(); // set recipients and other fields. email.settoaddresses(new string[] {'[email protected]'}); // append the threading token to the email body (text or html), subject, // or both body and subject. email.setplaintextbody('test email notification text body' + '\n\n' + formattedtoken); email.sethtmlbody('test email notification html body' + '<br><br>' + formattedtoken); email.setsubject('test notification ' + '[ ' + formattedtoken + ' ]'); // ........... more fields ........... // send out the email. messaging.sendemail(new messaging.singleemailmessage[]{email}); getrecordidfromemail(subject, textbody, htmlbody) returns the record id corresponding to the specified email threading token, or returns null if none is found. signature public static id getrecordidfromemail(string subject, string textbody, string htmlbody) 3012apex reference guide emailmessages class parameters subject type: string the subject of the email. textbody type: string the body of the email in text format. htmlbody type: string the body of the email in html format. return value type: id the record id that corresponds to the embedded threading token. usage requires lightning threading to be enabled in email-to-case. when you send emails with threading tokens embedded in the email subject, the email body, or in both the subject and body, most email clients quote the email body and maintain the email subject in a response. this method finds a corresponding record that matches the embedded threading token in a response. typically this method is used in email services so that you can provide your own handling of inbound emails using apex code. example if you implement header-based threading in your email services currently, we recommend that you use lightning threading, which combines token-based threading and header-based threading. for header-based threading to continue to work, store emails as emailmessage records with the messagedidentifier field set properly. with lightning threading, you can use threading tokens as the primary threading method and rely on header-based threading as a fallback, or vice versa. in this example, we rely on threading tokens and use header-based threading as a fallback. global class attachemailmessagetocaseexample implements messaging.inboundemailhandler { global messaging.inboundemailresult handleinboundemail(messaging.inboundemail email, messaging.inboundenvelope env) { // create an inboundemailresult object for returning the result of the // apex email service. messaging.inboundemailresult result = new messaging.inboundemailresult(); // try to find the case id using threading tokens in email attributes. id caseid = emailmessages.getrecordidfromemail(email.subject, email.plaintextbody, email.htmlbody); // if we haven't found the case id, try finding it using headers. if (caseid == null) { caseid = cases.getcaseidfromemailhead |
ers(email.headers); 3013apex reference guide emailmessages class } // if a case isn’t found, create a new case record. if (caseid == null) { case c = new case(subject = email.subject); insert c; system.debug('new case object: ' + c); caseid = c.id; } // process recipients string toaddresses; if (email.toaddresses != null) { toaddresses = string.join(email.toaddresses, '; '); } // to store an emailmessage for threading, you need at minimum // the status, the messageidentifier, and the parentid fields. emailmessage em = new emailmessage( status = '0', messageidentifier = email.messageid, parentid = caseid, // other important fields. fromaddress = email.fromaddress, fromname = email.fromname, toaddress = toaddresses, textbody = email.plaintextbody, htmlbody = email.htmlbody, subject = email.subject, // parse thread-index header to remain consistent with email-to-case. clientthreadidentifier = getclientthreadidentifier(email.headers) // other fields you wish to add. ); // insert the new emailmessage. insert em; system.debug('new emailmessage object: ' + em ); // set the result to true. no need to send an email back to the user // with an error message. result.success = true; // return the result for the apex email service. return result; } private string getclientthreadidentifier(list<messaging.inboundemail.header> headers) { if (headers == null || headers.size() == 0) return null; try { for (messaging.inboundemail.header header : headers) { if (header.name.equalsignorecase('thread-index')) { blob threadindex = encodingutil.base64decode(header.value.trim()); return encodingutil.converttohex(threadindex).substring(0, 44).touppercase(); 3014apex reference guide encodingutil class } } } catch (exception e){ return null; } return null; } } encodingutil class use the methods in the encodingutil class to encode and decode url strings, and convert strings to hexadecimal format. namespace system usage note: you cannot use the encodingutil methods to move documents with non-ascii characters to salesforce. you can, however, download a document from salesforce. to do so, query the id of the document using the api query call, then request it by id. encodingutil methods the following are methods for encodingutil. all methods are static. in this section: base64decode(inputstring) converts a base64-encoded string to a blob representing its normal form. base64encode(inputblob) converts a blob to an unencoded string representing its normal form. convertfromhex(inputstring) converts the specified hexadecimal (base 16) string to a blob value and returns this blob value. converttohex(inputblob) returns a hexadecimal (base 16) representation of the inputblob. this method can be used to compute the client response (for example, ha1 or ha2) for http digest authentication (rfc2617). urldecode(inputstring, encodingscheme) decodes a string in application/x-www-form-urlencoded format using a specific encoding scheme, for example “utf-8.” urlencode(inputstring, encodingscheme) encodes a string into the application/x-www-form-urlencoded format using a specific encoding scheme, for example “utf-8.” 3015apex reference guide encodingutil class base64decode(inputstring) converts a base64-encoded string to a blob representing its normal form. signature public static blob base64decode(string inputstring) parameters inputstring type: string return value type: blob base64encode(inputblob) converts a blob to an unencoded string representing its normal form. signature public static string base64encode(bl |
ob inputblob) parameters inputblob type: blob return value type: string convertfromhex(inputstring) converts the specified hexadecimal (base 16) string to a blob value and returns this blob value. signature public static blob convertfromhex(string inputstring) parameters inputstring type: string the hexadecimal string to convert. the string can contain only valid hexadecimal characters (0-9, a-f, a-f) and must have an even number of characters. 3016apex reference guide encodingutil class return value type: blob usage each byte in the blob is constructed from two hexadecimal characters in the input string. the convertfromhex method throws the following exceptions. • nullpointerexception — the inputstring is null. • invalidparametervalueexception — the inputstring contains invalid hexadecimal characters or doesn’t contain an even number of characters. example blob blobvalue = encodingutil.convertfromhex('4a4b4c'); system.assertequals('jkl', blobvalue.tostring()); converttohex(inputblob) returns a hexadecimal (base 16) representation of the inputblob. this method can be used to compute the client response (for example, ha1 or ha2) for http digest authentication (rfc2617). signature public static string converttohex(blob inputblob) parameters inputblob type: blob return value type: string urldecode(inputstring, encodingscheme) decodes a string in application/x-www-form-urlencoded format using a specific encoding scheme, for example “utf-8.” signature public static string urldecode(string inputstring, string encodingscheme) parameters inputstring type: string encodingscheme type: string 3017apex reference guide enum methods return value type: string usage this method uses the supplied encoding scheme to determine which characters are represented by any consecutive sequence of the form \"%xy\". for more information about the format, see the form-urlencoded media type in hypertext markup language - 2.0. urlencode(inputstring, encodingscheme) encodes a string into the application/x-www-form-urlencoded format using a specific encoding scheme, for example “utf-8.” signature public static string urlencode(string inputstring, string encodingscheme) parameters inputstring type: string encodingscheme type: string return value type: string usage this method uses the supplied encoding scheme to obtain the bytes for unsafe characters. for more information about the format, see the form-urlencoded media type in hypertext markup language - 2.0. example string encoded = encodingutil.urlencode(url, 'utf-8'); enum methods an enum is an abstract data type with values that each take on exactly one of a finite set of identifiers that you specify. apex provides built-in enums, such as logginglevel, and you can define your own enum. all apex enums, whether user-defined enums or built-in enums, have these common methods: values this method returns the values of the enum as a list of the same enum type. valueof(string enumstr) this method converts a specified string to an enum constant value. an exception is thrown if the input string doesn’t match an enum value. 3018apex reference guide eventbus class each enum value has the following methods that take no arguments. name returns the name of the enum item as a string. ordinal returns the position of the item, as an integer, in the list of enum values starting with zero. enum values cannot have user-defined methods added to them. for more information about enum, see enums. example integer i = statuscode.delete_failed.ordinal(); string s = statuscode.delete_failed.name(); list<statuscode> values = statuscode.values(); statuscode statuscodevalue = statuscode.valueof('delete_failed'); eventbus class contains methods for publishing platform events. namespace system in this section: eventbus methods see also: platform events developer guide: publishing platform events eventbus methods |
the following are methods for eventbus. all methods are static. in this section: getoperationid(result) returns the event uuid, which identifies a published event message. publish(event) publishes the given platform event. publish(events) publishes the given list of platform events. 3019apex reference guide eventbus class getoperationid(result) returns the event uuid, which identifies a published event message. signature public static string getoperationid(object result) parameters result type: object the saveresult that is returned by the eventbus.publish call. return value type: string publish(event) publishes the given platform event. signature public static database.saveresult publish(sobject event) parameters event type: sobject an instance of a platform event. for example, an instance of myevent__e. you must first define your platform event object in your org. return value type: database.saveresult the result of publishing the given event. database.saveresult contains information about whether the operation was successful and the errors encountered. if the issuccess() method returns true, the publish request is queued in salesforce and the event message is published asynchronously. for more information, see high-volume platform event persistence. if issuccess() returns false, the event publish operation resulted in errors, which are returned in the database.error object. this method doesn’t throw an exception due to an unsuccessful publish operation. database.saveresult also contains the id system field. the id field value isn’t included in the event message delivered to subscribers. it isn’t used to identify an event message, and isn’t always unique. usage • the platform event message is published either immediately or after a transaction is committed, depending on the publish behavior you set in the platform event definition. for more information, see platform event fields in the platform events developer guide. 3020apex reference guide exception class and built-in exceptions • apex governor limits apply. for events configured with the publish after commit behavior, each method execution is counted as one dml statement against the apex dml statement limit. you can check limit usage using the apex limits.getdmlstatements() on page 3115 method. for events configured with the publish immediately behavior, each method execution is counted against a separate event publishing limit of 150 eventbus.publish() calls. you can check limit usage using the apex limits.getpublishimmediatedml() on page 3118 method. publish(events) publishes the given list of platform events. signature public static list<database.saveresult> publish(list<sobject> events) parameters events type: list<sobject> a list of platform event instances. for example, a list of myevent__e objects. you must first define your platform event object in your salesforce org. return value type: list<database.saveresult> a list of results, each corresponding to the result of publishing one event. for each event, database.saveresult contains information about whether the operation was successful and the errors encountered. if the issuccess() method returns true, the publish request is queued in salesforce and the event message is published asynchronously. for more information, see high-volume platform event persistence. if issuccess() returns false, the event publish operation resulted in errors, which are returned in the database.error object. eventbus.publish() can publish some passed-in events, even when other events can’t be published due to errors. the eventbus.publish() method doesn’t throw exceptions caused by an unsuccessful publish operation. it’s similar in behavior to the apex database.insert method when called with the partial success option. database.saveresult also contains the id system field. the id field value isn’t included in the event message delivered to subscribers. it isn’t used to identify an event message, and isn’t always unique. usage • the platform event message is published either immediately or after a transaction is committed, depending on the publish behavior you set in the platform event definition. for more information, see platform event fields in the platform events developer guide. • apex governor limits apply. for events configured with the publish after commit behavior, each method execution is counted as one dml statement against the apex dml statement limit. you can check limit usage using the apex limits.getdmlstatements() on page 3115 method. for events configured with the publish immediately behavior, each method execution |
is counted against a separate event publishing limit of 150 eventbus.publish() calls. you can check limit usage using the apex limits.getpublishimmediatedml() on page 3118 method. exception class and built-in exceptions an exception denotes an error that disrupts the normal flow of code execution. you can use apex built-in exceptions or create custom exceptions. all exceptions have common methods. 3021apex reference guide exception class and built-in exceptions all exceptions support built-in methods for returning the error message and exception type. in addition to the standard exception class, there are several different types of exceptions: the following are exceptions in the system namespace. exception description assertexception a system.assert failure that halts code execution. optionally contains the custom message specified in the last (msg) argument to the assert() method. auraexception legacy aura-related exception. use system.aurahandledexception instead. aurahandledexception returns a custom error message to a javascript controller. see returning errors from an apex server-side controller. asyncexception any problem with an asynchronous operation, such as failing to enqueue an asynchronous call. bigobjectexception any problem with big object records, such as connection timeouts during attempts to access or insert big object records. calloutexception any problem with a web service operation, such as failing to make a callout to an external system. dataweavescriptexception any run-time script errors that occur within dataweave in apex. dmlexception any problem with a dml statement, such as an insert statement missing a required field on a record. emailexception any problem with email, such as failure to deliver. for more information, see outbound email. externalobjectexception any problem with external object records, such as connection timeouts during attempts to access the data that’s stored on external systems. finalexception any attempt to mutate a read-only collection or record such as an sobject in an after-update trigger, or a final variable. this exception causes execution to halt. flowexception any problem with starting flow interviews from apex. for example, if an active version of the flow can’t be found or it can’t be started from apex. handledexception a generic handled exception. illegalargumentexception an illegal argument was provided to a method call. for example, a method that requires a non-null argument throws this exception if a null value is passed into the method. invalidheaderexception an illegal header argument was provided to an apex rest call. for example, a call to the restresponse.addheader(name, value) method throws this exception if the header name is cookie. invalidparametervalueexception this exception is used with both visualforce pages and salesforce functions. visualforce the exception is thrown when an invalid parameter is supplied for a method, or any problem is encountered with a url used with visualforce pages. for more information on visualforce, see the visualforce developer's guide. 3022apex reference guide exception class and built-in exceptions exception description salesforce functions the exception is thrown when the functionname parameter to function.get() doesn’t have the correct project name.function name format. for more information on salesforce functions, see function.get(). limitexception a governor limit has been exceeded. this exception can’t be caught. jsonexception any problem with json serialization and deserialization operations. for more information, see the methods of system.json, system.jsonparser, and system.jsongenerator. listexception any problem with a list, such as attempting to access an index that is out of bounds. mathexception any problem with a mathematical operation, such as dividing by zero. noaccessexception any problem with unauthorized access, such as trying to access an sobject that the current user doesn’t have access to. this exception is used with visualforce pages. for more information on visualforce, see the visualforce developer's guide. nodatafoundexception this exception is used with both visualforce pages and salesforce functions. visualforce the exception is thrown with data that doesn't exist, such as trying to access an sobject that has been deleted. for more information on visualforce, see the visualforce developer's guide. salesforce functions the exception is thrown when the project or function name provided in the functionname parameter to the function.get() method can't be found. for more information on salesforce functions, see function.get(). nosuchelementexception this exception is thrown if you try to access items that are outside the bounds of a list. this exception is used by the iter |
ator next method. for example, if iterator.hasnext() == false and you call iterator.next(), this exception is thrown. this exception is also used by the apex flex queue methods and is thrown if you attempt to access a job at an invalid position in the flex queue. nullpointerexception any problem with dereferencing null, such as in the following code: string s; s.tolowercase(); // since s is null, this call causes // a nullpointerexception queryexception any problem with soql queries, such as assigning a query that returns no records or more than one record to a singleton sobject variable. requiredfeaturemissing a chatter feature is required for code that has been deployed to an organization that doesn’t have chatter enabled. 3023apex reference guide exception class and built-in exceptions exception description searchexception any problem with sosl queries executed with soap api search() call, for example, when the searchstring parameter contains fewer than two characters. for more information, see the soap api developer guide. securityexception any problem with static methods in the crypto utility class. for more information, see crypto class. serializationexception any problem with the serialization of data. this exception is used with visualforce pages. for more information on visualforce, see the visualforce developer's guide. sobjectexception any problem with sobject records, such as attempting to change a field in an update statement that can only be changed during insert. stringexception any problem with strings, such as a string that is exceeding your heap size. typeexception any problem with type conversions, such as attempting to convert the string 'a' to an integer using the valueof method. unexpectedexception a non-recoverable internal error within salesforce has occurred. this exception causes execution to halt. if necessary, contact salesforce customer support for more information. visualforceexception any problem with a visualforce page. for more information on visualforce, see the visualforce developer's guide. xmlexception any problem with the xmlstream classes, such as failing to read or write xml. the following is an example using the dmlexception exception: account[] accts = new account[]{new account(billingcity = 'san jose')}; try { insert accts; } catch (system.dmlexception e) { for (integer i = 0; i < e.getnumdml(); i++) { // process exception here system.debug(e.getdmlmessage(i)); } } for exceptions in other namespaces, see: • cache exceptions • canvas exceptions • connectapi exceptions • datasource exceptions • reports exceptions • site exceptions common exception methods exception methods are all called by and operate on an instance of an exception. this table describes all instance exception methods. all types of exceptions have these methods in common. 3024apex reference guide exception class and built-in exceptions name arguments return type description getcause exception returns the cause of the exception as an exception object. getlinenumber integer returns the line number from where the exception was thrown. getmessage string returns the error message that displays for the user. getstacktracestring string returns the stack trace of a thrown exception as a string. gettypename string returns the type of exception, such as dmlexception, listexception, mathexception, and so on. initcause exception cause void sets the cause for this exception, if one hasn’t already been set. setmessage string s void sets the error message that displays for the user. dmlexception and emailexception methods in addition to the common exception methods, dmlexception and emailexception have these methods: name arguments return type description getdmlfieldnames integer i string [] returns the names of the field or fields that caused the error described by the ith failed row. getdmlfields integer i schema.sobjectfield [] returns the field token or tokens for the field or fields that caused the error described by the ith failed row. for more information on field tokens, see dynamic apex. getdmlid integer i string returns the id of the failed record that caused the error described by the ith failed row. getdmlindex integer i integer returns the original row position of the ith failed row. getdmlmessage integer i string returns the user message for the ith failed row. getdmlstatuscode integer i string deprecated. use getdmltype instead. returns the apex failure code for the ith failed |
row. getdmltype integer i system.statuscode returns the value of the system.statuscode enum. for example: try { insert new account(); } catch (system.dmlexception ex) { system.assertequals( statuscode.required_field_missing, ex.getdmltype(0)); } for more information about system.statuscode, see enums. 3025apex reference guide flexqueue class name arguments return type description getnumdml integer returns the number of failed rows for dml exceptions. queryexception method in addition to the common exception methods, queryexception has this method. name arguments return type description getinaccessiblefields map on page returns a map in which each key is an sobjecttype 3144<string,set< on and its corresponding value is the set of inaccessible field page 3279string>> names in fully qualified format (namespace__fieldname__c). use this method to determine the cause of the queryexception. the returned map contains data only if the method that threw the queryexception is running in user mode (as opposed to the default system mode). in this code sample, it's assumed that the user doesn’t have field level security access to the contact.email and account.website fields. try { list<account> accounts = [select website, (select email from contacts) from account with user_mode]; } catch (queryexception qe) { // handle inaccessible fields map<string, set<string>> inaccessible = qe.getinaccessiblefields(); set<string> accountfields = inaccessible.get('account'); set<string> contactfields = inaccessible.get('contact'); } flexqueue class contains methods that reorder batch jobs in the apex flex queue. namespace system 3026apex reference guide flexqueue class usage you can place up to 100 batch jobs in a holding status for future execution. when system resources become available, the jobs are taken from the top of the apex flex queue and moved to the batch job queue. up to five queued or active jobs can be processed simultaneously for each org. when a job is moved out of the flex queue for processing, its status changes from holding to queued. queued jobs are executed when the system is ready to process new jobs. use this class’s methods to reorder your holding jobs in the flex queue. as best practice and for safe usage, a flexqueue reorder method must be the final statement in a transaction. example this example moves a job to the front of the flex queue so that it’s executed immediately. the job is moved by calling the system.flexqueue.movejobtofront() method with the high priority job id as the parameter. id highpriorityjobid = database.executebatch(new highprioritybatchclass(), 200); boolean jobmovedtofrontofqueue = flexqueue.movejobtofront(highpriorityjobid); in this section: flexqueue methods see also: monitoring the apex flex queue apex developer guide: using batch apex flexqueue methods the following are methods for flexqueue. in this section: moveafterjob(jobtomoveid, jobinqueueid) moves the job with the id jobtomoveid immediately after the job with the id jobinqueueid in the flex queue. you can move jobtomoveid forward or backward in the queue. if either job isn’t in the queue, it throws an element-not-found exception. returns true if the job is moved, or false if jobtomoveid is already immediately after jobinqueueid, so no change is made. movebeforejob(jobtomoveid, jobinqueueid) moves the job with the id jobtomoveid immediately before the job with the id jobinqueueid in the flex queue. you can move jobtomoveid forward or backward in the queue. if either job isn’t in the queue, it throws an element-not-found exception. returns true if the job is moved, or false if jobtomoveid is already immediately before jobinqueueid, so no change is made. movejobtoend(jobid) moves the specified job the end of the flex queue, to index position (size - 1). all jobs after the job’s starting position move one spot forward. if the job isn’t in the queue, it throws an element-not-found exception. |
returns true if the job is moved, or false if the job is already at the end of the queue, so no change is made. 3027apex reference guide flexqueue class movejobtofront(jobid) moves the specified job to the front of the flex queue, to index position 0. all other jobs move back one spot. if the job isn’t in the queue, it throws an element-not-found exception. returns true if the job is moved, or false if the job is already at the front of the queue, so no change is made. moveafterjob(jobtomoveid, jobinqueueid) moves the job with the id jobtomoveid immediately after the job with the id jobinqueueid in the flex queue. you can move jobtomoveid forward or backward in the queue. if either job isn’t in the queue, it throws an element-not-found exception. returns true if the job is moved, or false if jobtomoveid is already immediately after jobinqueueid, so no change is made. signature public static boolean moveafterjob(id jobtomoveid, id jobinqueueid) parameters jobtomoveid type: id the id of the job to move. jobinqueueid type: id the id of the job to move after. return value type: boolean movebeforejob(jobtomoveid, jobinqueueid) moves the job with the id jobtomoveid immediately before the job with the id jobinqueueid in the flex queue. you can move jobtomoveid forward or backward in the queue. if either job isn’t in the queue, it throws an element-not-found exception. returns true if the job is moved, or false if jobtomoveid is already immediately before jobinqueueid, so no change is made. signature public static boolean movebeforejob(id jobtomoveid, id jobinqueueid) parameters jobtomoveid type: id the id of the job to move. jobinqueueid type: id the id of the job to use as a reference point. 3028apex reference guide featuremanagement class return value type: boolean movejobtoend(jobid) moves the specified job the end of the flex queue, to index position (size - 1). all jobs after the job’s starting position move one spot forward. if the job isn’t in the queue, it throws an element-not-found exception. returns true if the job is moved, or false if the job is already at the end of the queue, so no change is made. signature public static boolean movejobtoend(id jobid) parameters jobid type: id the id of the job to move. return value type: boolean movejobtofront(jobid) moves the specified job to the front of the flex queue, to index position 0. all other jobs move back one spot. if the job isn’t in the queue, it throws an element-not-found exception. returns true if the job is moved, or false if the job is already at the front of the queue, so no change is made. signature public static boolean movejobtofront(id jobid) parameters jobid type: id the id of the job to move. return value type: boolean featuremanagement class use the methods in the system.featuremanagement class to check and modify the values of feature parameters, and to show or hide custom objects and custom permissions in your subscribers’ orgs. 3029apex reference guide featuremanagement class namespace system usage for information about feature parameters, see manage features in second generation managed packages in the salesforce dx developer guide, or manage features in first-generation managed packages in the isvforce guide. the set methods (setpackagebooleanvalue, setpackagedatevalue, setpackageintegervalue) use dml operations on setup sobjects. to learn more about mixing operations in a test, see mixed dml operations in test methods. in this section: featuremanagement methods featuremanagement methods the following are methods for featuremanagement. in this section: changeprotection(apiname, typeapiname, protection) hides or reveals custom permissions, or reveals custom objects, in your subscriber’s org. checkpackagebooleanvalue(apiname) checks the value__c value of the featureparameterboolean__c record for a feature parameter in your subscriber’s org. |
you set the record’s value using setpackagebooleanvalue(apiname, value). checkpackagedatevalue(apiname) checks the value__c value of the featureparameterdate__c record for a feature parameter in your subscriber’s org. you can set the record’s value using setpackagedatevalue(apiname, value). checkpackageintegervalue(apiname) checks the value__c value of the featureparameterinteger__c record for a feature parameter in your subscriber’s org. you can set the record’s value using setpackageintegervalue(apiname, value). checkpermission(apiname) checks whether a custom permission is enabled. setpackagebooleanvalue(apiname, value) sets the value__c value of the featureparameterboolean__c record for a subscriber-to-lmo feature parameter in your subscriber’s org. you can check the record’s value using checkpackagebooleanvalue(apiname). setpackagedatevalue(apiname, value) sets the value__c value of the featureparameterdate__c record for a subscriber-to-lmo feature parameter in your subscriber’s org. you can check the record’s value using checkpackagedatevalue(apiname). setpackageintegervalue(apiname, value) sets the value__c value of the featureparameterinteger__c record for a subscriber-to-lmo feature parameter in your subscriber’s org. you can check the record’s value using checkpackageintegervalue(apiname). 3030apex reference guide featuremanagement class changeprotection(apiname, typeapiname, protection) hides or reveals custom permissions, or reveals custom objects, in your subscriber’s org. signature public static void changeprotection(string apiname, string typeapiname, string protection) parameters apiname type: string the api name of the custom object or custom permission to show or hide—for example, 'mycustomobject__c' or 'mycustompermission'. typeapiname type: string the api name of the type that you want to show or hide: 'customobject' or 'custompermission'. protection type: string to show a custom object or custom permission, 'unprotected'. to hide a custom permission, 'protected'. return value type: void usage warning: for custom permissions, you can toggle the protected value indefinitely. however, after you’ve released unprotected objects to subscribers, you can’t set visibility to protected. be sure to protect any custom objects that you want to hide before you release the first package version that contains them. to hide custom permissions in released packages: featuremanagement.changeprotection('yourcustompermissionname', 'custompermission', 'protected'); to unhide custom permissions and custom objects in released packages: featuremanagement.changeprotection('yourcustompermissionname', 'custompermission', 'unprotected'); featuremanagement.changeprotection('yourcustomobjectname__c', 'customobject', 'unprotected'); checkpackagebooleanvalue(apiname) checks the value__c value of the featureparameterboolean__c record for a feature parameter in your subscriber’s org. you set the record’s value using setpackagebooleanvalue(apiname, value). 3031apex reference guide featuremanagement class signature public static boolean checkpackagebooleanvalue(string apiname) parameters apiname type: string the fullname__c value of the feature parameter whose value you want to check—for example, 'specialaccessavailable'. return value type: boolean the value that’s currently assigned to the value__c field on the featureparameterboolean__c record that associates the feature parameter with its related license. checkpackagedatevalue(apiname) checks the value__c value of the featureparameterdate__c record for a feature parameter in your subscriber’s org. you can set the record’s value using setpackagedatevalue(apiname, value). signature public static date checkpackagedatevalue(string apiname) parameters apiname type: string the fullname__c value of the feature parameter whose value you want to check—for example, 'trialexpirationdate'. return value type: date the value that’s currently assigned to the value__c field on the featureparameterdate__c record that associates the feature parameter with its related license. checkpackageintegervalue(apiname) |
checks the value__c value of the featureparameterinteger__c record for a feature parameter in your subscriber’s org. you can set the record’s value using setpackageintegervalue(apiname, value). signature public static integer checkpackageintegervalue(string apiname) 3032 |
apex reference guide featuremanagement class parameters apiname type: string the fullname__c value of the feature parameter whose value you want to check—for example, 'numberoflicenses'. return value type: integer the value that’s currently assigned to the value__c field on the featureparameterinteger__c record that associates the feature parameter with its related license. checkpermission(apiname) checks whether a custom permission is enabled. signature public static boolean checkpermission(string apiname) parameters apiname type: string the api name of the custom permission to check the value of—for example, 'mycustompermission'. return value type: boolean shows whether the permission is enabled (true) or disabled (false). setpackagebooleanvalue(apiname, value) sets the value__c value of the featureparameterboolean__c record for a subscriber-to-lmo feature parameter in your subscriber’s org. you can check the record’s value using checkpackagebooleanvalue(apiname). signature public static void setpackagebooleanvalue(string apiname, boolean value) parameters apiname type: string the fullname__c value of the feature parameter whose value you want to set—for example, 'specialaccessavailable'. value type: boolean 3033apex reference guide featuremanagement class the value to assign to the value__c field on the featureparameterboolean__c record that associates the feature parameter with its related license. return value type: void setpackagedatevalue(apiname, value) sets the value__c value of the featureparameterdate__c record for a subscriber-to-lmo feature parameter in your subscriber’s org. you can check the record’s value using checkpackagedatevalue(apiname). signature public static void setpackagedatevalue(string apiname, date value) parameters apiname type: string the fullname__c value of the feature parameter whose value you want to set—for example, 'trialexpirationdate'. value type: date the value to assign to the value__c field on the featureparameterdate__c record that associates the feature parameter with its related license. return value type: void setpackageintegervalue(apiname, value) sets the value__c value of the featureparameterinteger__c record for a subscriber-to-lmo feature parameter in your subscriber’s org. you can check the record’s value using checkpackageintegervalue(apiname). signature public static void setpackageintegervalue(string apiname, integer value) parameters apiname type: string the fullname__c value of the feature parameter whose value you want to set—for example, 'numberoflicenses'. value type: integer the value to assign to the value__c field on the featureparameterinteger__c record that associates the feature parameter with its related license. 3034apex reference guide formula class return value type: void formula class contains the recalculateformulas method that updates (recalculates) all formula fields on the input sobjects. namespace system usage recalculate formula fields on new or queried sobjects. if all data is present on the sobjects, soql limits are not affected. if the data required to evaluate a formula field is missing, that data is loaded and limits are changed accordingly. the new formula values are stored in the sobjects themselves and overwrite previous values of formula fields. example account a = new account(); a.name = 'salesforce'; a.billingcity = 'san francisco'; list<account> accounts = new list<account>{a}; list<formularecalcresult> results = formula.recalculateformulas(accounts); system.assert(results[0].issuccess()); // option 1 system.debug('new value: ' + accounts[0].get('my_formula_field__c')); // option 2 system.debug('new value: ' + results[0].getsobject().get(‘my_formula_field__c’)); in this section: formula methods formula methods the following are methods for formula. in this section: recalculateformulas(sobjects) updates (recalculates) all formula fields on the input sobjects. recalculateformulas(sobject |
s) updates (recalculates) all formula fields on the input sobjects. 3035apex reference guide formularecalcfielderror class signature public static list<system.formularecalcresult> recalculateformulas(list<sobject> sobjects) parameters sobjects type: list<sobject> list of sobjects whose formula fields are to be recalculated. return value type: list<formularecalcresult class> formularecalcfielderror class the return type of the formularecalcresult.geterrors method. namespace system in this section: formularecalcfielderror methods formularecalcfielderror methods the following are methods for formularecalcfielderror. in this section: getfielderror() returns a message describing the errors encountered during formula recalculation. getfieldname() returns the name of the formula recalculation error field. getfielderror() returns a message describing the errors encountered during formula recalculation. signature public string getfielderror() return value type: string 3036apex reference guide formularecalcresult class getfieldname() returns the name of the formula recalculation error field. signature public string getfieldname() return value type: string formularecalcresult class the return type of the formula.recalculateformulas method. namespace system usage indicates the result and status of recalculating formulas on a single sobject. holds a reference to the sobject and a list of all the fields that were recalculated. example this example assumes that you have a formula field called divide__c with formula “1 / len(name). list<account> accounts = [select name from account where name='acme']; accounts[0].name = ''; list<formularecalcresult> results = formula.recalculateformulas(accounts); formularecalcresult result0 = results[0]; formularecalcfielderror fielderror = result0.geterrors()[0]; system.debug(fielderror.getfieldname()); // 'divide' system.debug(fielderror.getfielderror()); // 'division by zero' in this section: formularecalcresult methods formularecalcresult methods the following are methods for formularecalcresult. in this section: geterrors() if an error occurs during formula recalculation, an array of one or more database error objects, along with error codes and descriptions, is returned. 3037apex reference guide http class getsobject() returns the sobject with formulas recalculated. issuccess() returns a boolean value that is set to true if the formula recalculation process completed successfully; otherwise, it is set to false. geterrors() if an error occurs during formula recalculation, an array of one or more database error objects, along with error codes and descriptions, is returned. signature public list<system.formularecalcfielderror> geterrors() return value type: list<formularecalcfielderror class> getsobject() returns the sobject with formulas recalculated. signature public sobject getsobject() return value type: sobject issuccess() returns a boolean value that is set to true if the formula recalculation process completed successfully; otherwise, it is set to false. signature public boolean issuccess() return value type: boolean http class use the http class to initiate an http request and response. namespace system 3038apex reference guide httpcalloutmock interface http methods the following are methods for http. all are instance methods. in this section: send(request) sends an httprequest and returns the response. tostring() returns a string that displays and identifies the object's properties. send(request) sends an httprequest and returns the response. signature public httpresponse send(httprequest request) parameters request type: system.httprequest return value type: system.httpresponse tostring() returns a string that displays and identifies the object's properties. signature public string tostring() return value type: string httpcalloutmock interface enables sending fake responses when testing http callouts. namespace system 3039apex reference guide httprequest class usage |
for an implementation example, see testing http callouts by implementing the httpcalloutmock interface. httpcalloutmock methods the following are methods for httpcalloutmock. in this section: respond(request) returns an http response for the given request. the implementation of this method is called by the apex runtime to send a fake response when an http callout is made after test.setmock has been called. respond(request) returns an http response for the given request. the implementation of this method is called by the apex runtime to send a fake response when an http callout is made after test.setmock has been called. signature public httpresponse respond(httprequest request) parameters request type: system.httprequest return value type: system.httpresponse httprequest class use the httprequest class to programmatically create http requests like get, post, patch, put, and delete. namespace system usage use the xml classes or json classes to parse xml or json content in the body of a request created by httprequest. example the following example illustrates how you can use an authorization header with a request and handle the response. public class authcallout { 3040apex reference guide httprequest class public void basicauthcallout(){ httprequest req = new httprequest(); req.setendpoint('http://www.yahoo.com'); req.setmethod('get'); // specify the required user name and password to access the endpoint // as well as the header and header information string username = 'myname'; string password = 'mypwd'; blob headervalue = blob.valueof(username + ':' + password); string authorizationheader = 'basic ' + encodingutil.base64encode(headervalue); req.setheader('authorization', authorizationheader); // create a new http object to send the request object // a response object is generated as a result of the request http http = new http(); httpresponse res = http.send(req); system.debug(res.getbody()); } } note: you can set the endpoint as a named credential url. a named credential url contains the scheme callout:, the name of the named credential, and an optional path. for example: callout:my_named_credential/some_path. a named credential specifies the url of a callout endpoint and its required authentication parameters in one definition. salesforce manages all authentication for apex callouts that specify a named credential as the callout endpoint so that your code doesn’t have to. see named credentials as callout endpoints. compression to compress the data you send, use setcompressed. httprequest req = new httprequest(); req.setendpoint('my_endpoint'); req.setcompressed(true); req.setbody('some post body'); if a response comes back in compressed format, getbody recognizes the format, uncompresses it, and returns the uncompressed value. in this section: httprequest constructors httprequest methods see also: apex developer guide: json support apex developer guide: xml support 3041apex reference guide httprequest class httprequest constructors the following are constructors for httprequest. in this section: httprequest() creates a new instance of the httprequest class. httprequest() creates a new instance of the httprequest class. signature public httprequest() httprequest methods the following are methods for httprequest. all are instance methods. in this section: getbody() retrieves the body of this request. getbodyasblob() retrieves the body of this request as a blob. getbodydocument() retrieves the body of this request as a dom document. getcompressed() if true, the request body is compressed, false otherwise. getendpoint() retrieves the url for the endpoint of the external server for this request. getheader(key) retrieves the contents of the request header. getmethod() returns the type of method used by httprequest. setbody(body) sets the contents of the body for this request. setbodyasblob(body) sets the contents of the body for this request using a blob. setbodydocument(document) sets the contents of the body for this request. the contents represent a dom document. set |
clientcertificate(clientcert, password) this method is deprecated. use setclientcertificatename instead. 3042apex reference guide httprequest class setclientcertificatename(certdevname) if the external service requires a client certificate for authentication, set the certificate name. setcompressed(flag) if true, the data in the body is delivered to the endpoint in the gzip compressed format. if false, no compression format is used. setendpoint(endpoint) specifies the endpoint for this request. setheader(key, value) sets the contents of the request header. setmethod(method) sets the type of method to be used for the http request. settimeout(timeout) sets a timeout for the request between 1 and 120,000 milliseconds. the timeout is the maximum time to wait for establishing the http connection. the same timeout is used for waiting for the request to start. when the request is executing, such as retrieving or posting data, the connection is kept alive until the request finishes. tostring() returns a string containing the url for the endpoint of the external server for this request and the method used, for example, endpoint=http://yourserver, method=post getbody() retrieves the body of this request. signature public string getbody() return value type: string getbodyasblob() retrieves the body of this request as a blob. signature public blob getbodyasblob() return value type: blob getbodydocument() retrieves the body of this request as a dom document. 3043apex reference guide httprequest class signature public dom.document getbodydocument() return value type: dom.document example use this method as a shortcut for: string xml = httprequest.getbody(); dom.document domdoc = new dom.document(xml); getcompressed() if true, the request body is compressed, false otherwise. signature public boolean getcompressed() return value type: boolean getendpoint() retrieves the url for the endpoint of the external server for this request. signature public string getendpoint() return value type: string getheader(key) retrieves the contents of the request header. signature public string getheader(string key) parameters key type: string 3044apex reference guide httprequest class return value type: string getmethod() returns the type of method used by httprequest. signature public string getmethod() return value type: string usage examples of return values: • delete • get • head • patch • post • put • trace setbody(body) sets the contents of the body for this request. signature public void setbody(string body) parameters body type: string return value type: void usage limit: 6 mb for synchronous apex or 12 mb for asynchronous apex. the http request and response sizes count towards the total heap size. 3045apex reference guide httprequest class setbodyasblob(body) sets the contents of the body for this request using a blob. signature public void setbodyasblob(blob body) parameters body type: blob return value type: void usage limit: 6 mb for synchronous apex or 12 mb for asynchronous apex. the http request and response sizes count towards the total heap size. setbodydocument(document) sets the contents of the body for this request. the contents represent a dom document. signature public void setbodydocument(dom.document document) parameters document type: dom.document return value type: void usage limit: 6 mb for synchronous apex or 12 mb for asynchronous apex. setclientcertificate(clientcert, password) this method is deprecated. use setclientcertificatename instead. signature public void setclientcertificate(string clientcert, string password) 3046apex reference guide httprequest class parameters clientcert type: string password type: string return value type: void usage if the server requires a client certificate for authentication, set the client certificate pkcs12 key store and password. setclientcertificatename(certdevname) if the external service requires a client certificate for authentication, set the certificate name. signature public void setclientcertificatename(string certdevname) |
parameters certdevname type: string return value type: void usage see using certificates with http requests. setcompressed(flag) if true, the data in the body is delivered to the endpoint in the gzip compressed format. if false, no compression format is used. signature public void setcompressed(boolean flag) parameters flag type: boolean 3047apex reference guide httprequest class return value type: void setendpoint(endpoint) specifies the endpoint for this request. signature public void setendpoint(string endpoint) parameters endpoint type: string possible values for the endpoint: • endpoint url https://my_endpoint.example.com/some_path • named credential url, which contains the scheme callout, the name of the named credential, and, optionally, an appended path callout:my_named_credential/some_path return value type: void see also: apex developer guide: named credentials as callout endpoints setheader(key, value) sets the contents of the request header. signature public void setheader(string key, string value) parameters key type: string value type: string 3048apex reference guide httprequest class return value type: void usage limit 100 kb. setmethod(method) sets the type of method to be used for the http request. signature public void setmethod(string method) parameters method type: string possible values for the method type include: • delete • get • head • patch • post • put • trace return value type: void usage you can also use this method to set any required options. settimeout(timeout) sets a timeout for the request between 1 and 120,000 milliseconds. the timeout is the maximum time to wait for establishing the http connection. the same timeout is used for waiting for the request to start. when the request is executing, such as retrieving or posting data, the connection is kept alive until the request finishes. signature public void settimeout(integer timeout) 3049apex reference guide httpresponse class parameters timeout type: integer return value type: void tostring() returns a string containing the url for the endpoint of the external server for this request and the method used, for example, endpoint=http://yourserver, method=post signature public string tostring() return value type: string httpresponse class use the httpresponse class to handle the http response returned by the http class. namespace system usage use the xml classes or json classes to parse xml or json content in the body of a response accessed by httpresponse. example in the following getxmlstreamreader example, content is retrieved via an http callout, then the xml is parsed using the xmlstreamreader class. public class readerfromcalloutsample { public void getandparse() { // get the xml document from the endpoint http http = new http(); httprequest req = new httprequest(); req.setendpoint(url.getorgdomainurl().toexternalform() + '/services/data'); req.setmethod('get'); req.setheader('accept', 'application/xml'); httpresponse res = http.send(req); // log the xml content 3050apex reference guide httpresponse class system.debug(res.getbody()); // generate the http response as an xml stream xmlstreamreader reader = res.getxmlstreamreader(); // read through the xml while(reader.hasnext()) { system.debug('event type:' + reader.geteventtype()); if (reader.geteventtype() == xmltag.start_element) { system.debug(reader.getlocalname()); } reader.next(); } } } see also: apex developer guide: json support apex developer guide: xml support httpresponse methods the following are methods for httpresponse. all are instance methods. in this section: getbody() retrieves the body returned in the response. getbodyasblob() retrieves the body returned in the response as a blob. getbodydocument() retrieves the body returned in the response as a dom document. getheader(key) retrieves the contents of the response header. |
getheaderkeys() retrieves an array of header keys returned in the response. getstatus() retrieves the status message returned for the response. getstatuscode() retrieves the value of the status code returned in the response. getxmlstreamreader() returns an xmlstreamreader that parses the body of the callout response. setbody(body) specifies the body returned in the response. 3051apex reference guide httpresponse class setbodyasblob(body) specifies the body returned in the response using a blob. setheader(key, value) specifies the contents of the response header. setstatus(status) specifies the status message returned in the response. setstatuscode(statuscode) specifies the value of the status code returned in the response. tostring() returns the status message and status code returned in the response, for example: getbody() retrieves the body returned in the response. signature public string getbody() return value type: string usage limit 6 mb for synchronous apex or 12 mb for asynchronous apex. the http request and response sizes count towards the total heap size. getbodyasblob() retrieves the body returned in the response as a blob. signature public blob getbodyasblob() return value type: blob usage limit 6 mb for synchronous apex or 12 mb for asynchronous apex. the http request and response sizes count towards the total heap size. getbodydocument() retrieves the body returned in the response as a dom document. 3052apex reference guide httpresponse class signature public dom.document getbodydocument() return value type: dom.document example use it as a shortcut for: string xml = httpresponse.getbody(); dom.document domdoc = new dom.document(xml); getheader(key) retrieves the contents of the response header. signature public string getheader(string key) parameters key type: string return value type: string getheaderkeys() retrieves an array of header keys returned in the response. signature public string[] getheaderkeys() return value type: string[] getstatus() retrieves the status message returned for the response. signature public string getstatus() 3053apex reference guide httpresponse class return value type: string getstatuscode() retrieves the value of the status code returned in the response. signature public integer getstatuscode() return value type: integer getxmlstreamreader() returns an xmlstreamreader that parses the body of the callout response. signature public xmlstreamreader getxmlstreamreader() return value type: system.xmlstreamreader usage use it as a shortcut for: string xml = httpresponse.getbody(); xmlstreamreader xsr = new xmlstreamreader(xml); setbody(body) specifies the body returned in the response. signature public void setbody(string body) parameters body type: string return value type: void 3054apex reference guide httpresponse class setbodyasblob(body) specifies the body returned in the response using a blob. signature public void setbodyasblob(blob body) parameters body type: blob return value type: void setheader(key, value) specifies the contents of the response header. signature public void setheader(string key, string value) parameters key type: string value type: string return value type: void setstatus(status) specifies the status message returned in the response. signature public void setstatus(string status) parameters status type: string 3055apex reference guide id class return value type: void setstatuscode(statuscode) specifies the value of the status code returned in the response. signature public void setstatuscode(integer statuscode) parameters statuscode type: integer return value type: void tostring() returns the status message and status code returned in the response, for example: signature public string tostring() return value type: string example status=ok, statuscode=200 id class contains methods for the id primitive data type. namespace system example: getting an sobject token from an id |
this sample shows how to use the getsobjecttype method to obtain an sobject token from an id. the updateowner method in this sample accepts a list of ids of the sobjects to update the ownerid field of. this list contains ids of sobjects of the same type. the second parameter is the new owner id. note that since it is a future method, it doesn’t accept sobject types as parameters; this is why 3056apex reference guide id class it accepts ids of sobjects. this method gets the sobject token from the first id in the list, then does a describe to obtain the object name and constructs a query dynamicallly. it then queries for all sobjects and updates their owner id fields to the new owner id. public class mydynamicsolution { @future public static void updateowner(list<id> objids, id newownerid) { // validate input system.assert(objids != null); system.assert(objids.size() > 0); system.assert(newownerid != null); // get the sobject token from the first id // (the list contains ids of sobjects of the same type). schema.sobjecttype token = objids[0].getsobjecttype(); // using the token, do a describe // and construct a query dynamically. schema.describesobjectresult dr = token.getdescribe(); string querystring = 'select ownerid from ' + dr.getname() + ' where '; for(id objid : objids) { querystring += 'id=\'' + objid + '\' or '; } // remove the last ' or' querystring = querystring.substring(0, querystring.length() - 4); sobject[] objdblist = database.query(querystring); system.assert(objdblist.size() > 0); // update the owner id on the sobjects for(integer i=0;i<objdblist.size();i++) { objdblist[i].put('ownerid', newownerid); } database.saveresult[] srlist = database.update(objdblist, false); for(database.saveresult sr : srlist) { if (sr.issuccess()) { system.debug('updated owner id successfully for ' + dr.getname() + ' id ' + sr.getid()); } else { system.debug('updating ' + dr.getname() + ' returned the following errors.'); for(database.error e : sr.geterrors()) { system.debug(e.getmessage()); } } } } } id methods the following are methods for id. 3057apex reference guide id class 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 error message and prevents any dml operation from occurring. getsobjecttype() returns the token for the sobject corresponding to this id. this method is primarily used with describe information. to15(id) converts an 18-character id value to a 15-character case-sensitive string. valueof(toid) converts the specified string into an id and returns the id. valueof(str, restorecasing) converts the specified string into an id and returns the id. if restorecasing is true, and the string represents an 18-character id that has incorrect casing, the method returns an 18-character id that is correctly aligned with its encoded casing. 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 this method is similar to the adderror(errormsg) sobject method. note: this method escapes any html markup in the specified error message. the escaped characters are: \n, <, >, &, ", \, \u2028, \u |
2029, and \u00a9. as a result, html markup is not rendered; instead, it is displayed as text in the salesforce user interface. 3058apex reference guide id class example trigger.new[0].id.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].id.adderror('fix & resubmit', false); adderror(exceptionerror) marks a trigger record with a custom error message and prevents any dml operation from occurring. 3059apex reference guide id 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 this method is similar to the adderror(exceptionerror) sobject method. 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 public class myexception extends exception{} trigger.new[0].id.adderror(new myexception('invalid id')); adderror(exceptionerror, escape) marks a trigger record with a custom error message 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 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 3060apex reference guide id class 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{} account a = new account(); a.adderror(new myexception('invalid id & other issues'), false); getsobjecttype() returns the token for the sobject corresponding to this id. this method is primarily used with describe information. signature public schema.sobjecttype getsobjecttype() return value type: schema.sobjecttype usage for more information about describes, see understanding |
apex describe information. example account a = new account(name = 'account'); insert a; id myid = a.id; system.assertequals(schema.account.sobjecttype, myid.getsobjecttype()); to15(id) converts an 18-character id value to a 15-character case-sensitive string. signature public static string to15() 3061apex reference guide id class return value type: string example string id_15_char = '0d5b000001dvm9t'; string id_18_char = '0d5b000001dvm9tkah'; id testid = id_18_char; system.assertequals(testid.to15(),id_15_char); valueof(toid) converts the specified string into an id and returns the id. signature public static id valueof(string toid) parameters toid type: string return value type: id example id myid = id.valueof('001xa000003dilo'); versioned behavior changes in api version 54.0 and later, assignment of an invalid 15 or 18 character id to a variable results in a system.stringexception exception. valueof(str, restorecasing) converts the specified string into an id and returns the id. if restorecasing is true, and the string represents an 18-character id that has incorrect casing, the method returns an 18-character id that is correctly aligned with its encoded casing. signature public static id valueof(string str, boolean restorecasing) parameters str type: string 3062apex reference guide ideas class string to be converted to an id restorecasing type: boolean if set to true, and str represents an 18-character id, the method returns an 18-character id that is correctly aligned with its casing. return value type: id the return value depends on both the str and the restorecasing parameter values. note: if the str is invalid, the method throws a system.stringexception exception. parameters restorecasing=true restorecasing=false valid 15-character str value because the 15-character input value can’t the method returns a 15-character id. be encoded for casing, the method throws a system.stringexception. valid 18-character str value the method returns an 18-character id that the method doesn’t attempt to correctly is correctly aligned with its encoded casing. align the casing of the 18-character id and returns an 18-character id. ideas class represents zone ideas. namespace system usage ideas is a zone of users who post, vote for, and comment on ideas. an ideas zone provides an online, transparent way for you to attract, manage, and showcase innovation. a set of recent replies (returned by methods, see below) includes ideas that a user posted or commented on that already have comments posted by another user. the returned ideas are listed based on the time of the last comment made by another user, with the most recent ideas appearing first. the userid argument is a required argument that filters the results so only the ideas that the specified user has posted or commented on are returned. the communityid argument filters the results so only the ideas within the specified zone are returned. if this argument is the empty string, then all recent replies for the specified user are returned regardless of the zone. for more information on ideas, see “using ideas” in the salesforce online help. 3063apex reference guide ideas class example the following example finds ideas in a specific zone that have similar titles as a new idea: public class findsimilarideascontroller { public static void test() { // instantiate a new idea idea idea = new idea (); // specify a title for the new idea idea.title = 'increase vacation time for employees'; // specify the communityid (internal_ideas) in which to find similar ideas. community community = [ select id from community where name = 'internal_ideas' ]; idea.communityid = community.id; id[] results = ideas.findsimilar(idea); } } the following example uses a visualforce page in conjunction with a custom controller, that is, a special apex class. for more information on visualforce, see the visualforce developer's guide. this example creates an apex method in the controller that returns unread recent replies. you can leverage this same example for the |
getallrecentreplies and getreadrecentreplies methods. for this example to work, there must be ideas posted to the zone. in addition, at least one zone member must have posted a comment to another zone member's idea or comment. // create an apex method to retrieve the recent replies marked as unread in all communities public class ideascontroller { public idea[] getunreadrecentreplies() { idea[] recentreplies; if (recentreplies == null) { id[] recentrepliesids = ideas.getunreadrecentreplies(userinfo.getuserid(), ''); recentreplies = [select id, title from idea where id in :recentrepliesids]; } return recentreplies; } } the following is the markup for a visualforce page that uses the above custom controller to list unread recent replies. <apex:page controller="ideascontroller" showheader="false"> <apex:datalist value="{!unreadrecentreplies}" var="recentreplyidea"> <a href="/apex/viewidea?id={!recentreplyidea.id}"> <apex:outputtext value="{!recentreplyidea.title}" escape="true"/></a> </apex:datalist> </apex:page> 3064apex reference guide ideas class the following example uses a visualforce page in conjunction with a custom controller to list ideas. then, a second visualforce page and custom controller is used to display a specific idea and mark it as read. for this example to work, there must be ideas posted to the zone. // create a controller to use on a visualforce page to list ideas public class idealistcontroller { public final idea[] ideas {get; private set;} public idealistcontroller() { integer i = 0; ideas = new idea[10]; for (idea tmp : database.query ('select id, title from idea where id != null and parentideaid = null limit 10')) { i++; ideas.add(tmp); } } } the following is the markup for a visualforce page that uses the above custom controller to list ideas: <apex:page controller="idealistcontroller" tabstyle="idea" showheader="false"> <apex:datalist value="{!ideas}" var="idea" id="idealist"> <a href="/apex/viewidea?id={!idea.id}"> <apex:outputtext value="{!idea.title}" escape="true"/></a> </apex:datalist> </apex:page> the following example also uses a visualforce page and custom controller, this time, to display the idea that is selected on the above idea list page. in this example, the markread method marks the selected idea and associated comments as read by the user that is currently logged in. note that the markread method is in the constructor so that the idea is marked read immediately when the user goes to a page that uses this controller. for this example to work, there must be ideas posted to the zone. in addition, at least one zone member must have posted a comment to another zone member's idea or comment. // create an apex method in the controller that marks all comments as read for the // selected idea public class viewideacontroller { private final string id = system.currentpage().getparameters().get('id'); public viewideacontroller(apexpages.standardcontroller controller) { ideas.markread(id); } } the following is the markup for a visualforce page that uses the above custom controller to display the idea as read. <apex:page standardcontroller="idea" extensions="viewideacontroller" showheader="false"> <h2><apex:outputtext value="{!idea.title}" /></h2> <apex:outputtext value="{!idea.body}" /> 3065apex reference guide ideas class </apex:page> ideas methods the following are methods for ideas. all methods are static. in this section: findsimilar(idea) returns a list of similar ideas based on the title of the specified idea. getallrecentreplies(userid, communityid) returns ideas that have recent replies for the specified user or zone. this includes all read and unread replies. getreadrecentreplies(userid, communityid) returns ideas that have recent replies marked as read. getunreadrecentreplies |
(userid, communityid) returns ideas that have recent replies marked as unread. markread(ideaid) marks all comments as read for the user that is currently logged in. findsimilar(idea) returns a list of similar ideas based on the title of the specified idea. signature public static id[] findsimilar(idea idea) parameters idea type: idea return value type: id[] usage each findsimilar call counts against the sosl query limits. see execution governors and limits. getallrecentreplies(userid, communityid) returns ideas that have recent replies for the specified user or zone. this includes all read and unread replies. signature public static id[] getallrecentreplies(string userid, string communityid) 3066apex reference guide ideas class parameters userid type: string communityid type: string return value type: id[] usage each getallrecentreplies call counts against the soql query limits. see execution governors and limits. getreadrecentreplies(userid, communityid) returns ideas that have recent replies marked as read. signature public static id[] getreadrecentreplies(string userid, string communityid) parameters userid type: string communityid type: string return value type: id[] usage each getreadrecentreplies call counts against the soql query limits. see execution governors and limits. getunreadrecentreplies(userid, communityid) returns ideas that have recent replies marked as unread. signature public static id[] getunreadrecentreplies(string userid, string communityid) parameters userid type: string 3067apex reference guide installhandler interface communityid type: string return value type: id[] usage each getunreadrecentreplies call counts against the soql query limits. see execution governors and limits. markread(ideaid) marks all comments as read for the user that is currently logged in. signature public static void markread(string ideaid) parameters ideaid type: string return value type: void installhandler interface enables custom code to run after a managed package installation or upgrade. namespace system usage app developers can implement this interface to specify apex code that runs automatically after a subscriber installs or upgrades a managed package. this makes it possible to customize the package install or upgrade, based on details of the subscriber’s organization. for instance, you can use the script to populate custom settings, create sample data, send an email to the installer, notify an external system, or kick off a batch operation to populate a new field across a large set of data. the post install script is invoked after tests have been run, and is subject to default governor limits. it runs as a special system user that represents your package, so all operations performed by the script appear to be done by your package. you can access this user by using userinfo. you will only see this user at runtime, not while running tests. if the script fails, the install/upgrade is aborted. any errors in the script are emailed to the user specified in the notify on apex error field of the package. if no user is specified, the install/upgrade details will be unavailable. the post install script has the following additional properties. 3068apex reference guide installhandler interface • it can initiate batch, scheduled, and future jobs. • it can’t access session ids. • it can only perform callouts using an async operation. the callout occurs after the script is run and the install is complete and committed. • it can’t call another apex class in the package if that apex class uses the with sharing keyword. this keyword can prevent the package from successfully installing. see the apex developer guide to learn more. the installhandler interface has a single method called oninstall, which specifies the actions to be performed on install/upgrade. global interface installhandler { void oninstall(installcontext context) }; the oninstall method takes a context object as its argument, which provides the following information. • the org id of the organization in which the installation takes place. • the user id of the user who initiated the installation. • the version number of the previously installed package (specified using the version class). this is always a three-part number, such as 1.2.0. • whether the installation is an upgrade. • whether the installation is a push. the context argument is an object whose type is the installcontext interface. this |
interface is automatically implemented by the system. the following definition of the installcontext interface shows the methods you can call on the context argument. global interface installcontext { id organizationid(); id installerid(); boolean isupgrade(); boolean ispush(); version previousversion(); } in this section: installhandler methods installhandler example implementation installhandler methods the following are methods for installhandler. in this section: oninstall(context) specifies the actions to be performed on install/upgrade. oninstall(context) specifies the actions to be performed on install/upgrade. 3069apex reference guide installhandler interface signature public void oninstall(installcontext context) parameters context type: system.installcontext return value type: void installhandler example implementation the following sample post install script performs these actions on package install/upgrade. • if the previous version is null, that is, the package is being installed for the first time, the script: – creates a new account called “newco” and verifies that it was created. – creates a new instance of the custom object survey, called “client satisfaction survey”. – sends an email message to the subscriber confirming installation of the package. • if the previous version is 1.0, the script creates a new instance of survey called “upgrading from version 1.0”. • if the package is an upgrade, the script creates a new instance of survey called “sample survey during upgrade”. • if the upgrade is being pushed, the script creates a new instance of survey called “sample survey during push”. global class postinstallclass implements installhandler { global void oninstall(installcontext context) { if(context.previousversion() == null) { account a = new account(name='newco'); insert(a); survey__c obj = new survey__c(name='client satisfaction survey'); insert obj; user u = [select id, email from user where id =:context.installerid()]; string toaddress= u.email; string[] toaddresses = new string[]{toaddress}; messaging.singleemailmessage mail = new messaging.singleemailmessage(); mail.settoaddresses(toaddresses); mail.setreplyto('[email protected]'); mail.setsenderdisplayname('my package support'); mail.setsubject('package install successful'); mail.setplaintextbody('thanks for installing the package.'); messaging.sendemail(new messaging.email[] { mail }); } else if(context.previousversion().compareto(new version(1,0)) == 0) { survey__c obj = new survey__c(name='upgrading from version 1.0'); insert(obj); } if(context.isupgrade()) { 3070apex reference guide integer class survey__c obj = new survey__c(name='sample survey during upgrade'); insert obj; } if(context.ispush()) { survey__c obj = new survey__c(name='sample survey during push'); insert obj; } } } you can test a post install script using the new testinstall method of the test class. this method takes the following arguments. • a class that implements the installhandler interface. • a version object that specifies the version number of the existing package. • an optional boolean value that is true if the installation is a push. the default is false. this sample shows how to test a post install script implemented in the postinstallclass apex class. @istest static void testinstallscript() { postinstallclass postinstall = new postinstallclass(); test.testinstall(postinstall, null); test.testinstall(postinstall, new version(1,0), true); list<account> a = [select id, name from account where name ='newco']; system.assertequals(a.size(), 1, 'account not found'); } integer class contains methods for the integer primitive data type. namespace system usage for more information on integers, see integer data type. integer methods the following are methods for integer. in this section: format() returns the integer as a string using the locale of the context user. valueof(stringtointeger) returns an integer that contains the value of the specified string. as in java, the string is interpreted as representing a signed decimal integer. 3071apex reference guide |
integer class valueof(fieldvalue) converts the specified object to an integer. use this method to convert a history tracking field value or an object that represents an integer value. format() returns the integer as a string using the locale of the context user. signature public string format() return value type: string example integer myint = 22; system.assertequals('22', myint.format()); valueof(stringtointeger) returns an integer that contains the value of the specified string. as in java, the string is interpreted as representing a signed decimal integer. signature public static integer valueof(string stringtointeger) parameters stringtointeger type: string return value type: integer example integer myint = integer.valueof('123'); valueof(fieldvalue) converts the specified object to an integer. use this method to convert a history tracking field value or an object that represents an integer value. 3072apex reference guide json class signature public static integer valueof(object fieldvalue) parameters fieldvalue type: object return value type: integer usage use this method with the oldvalue or newvalue fields of history sobjects, such as accounthistory, when the field type corresponds to an integer type, like a number field. example: example list<accounthistory> ahlist = [select field,oldvalue,newvalue from accounthistory]; for(accounthistory ah : ahlist) { system.debug('field: ' + ah.field); if (ah.field == 'numberofemployees') { integer oldvalue = integer.valueof(ah.oldvalue); integer newvalue = integer.valueof(ah.newvalue); } json class contains methods for serializing apex objects into json format and deserializing json content that was serialized using the serialize method in this class. namespace system usage use the methods in the system.json class to perform round-trip json serialization and deserialization of apex objects. see also: apex developer guide: roundtrip serialization and deserialization 3073apex reference guide json class json methods the following are methods for json. all methods are static. in this section: creategenerator(prettyprint) returns a new json generator. createparser(jsonstring) returns a new json parser. deserialize(jsonstring, apextype) deserializes the specified json string into an apex object of the specified type. deserializestrict(jsonstring, apextype) deserializes the specified json string into an apex object of the specified type. deserializeuntyped(jsonstring) deserializes the specified json string into collections of primitive data types. serialize(objecttoserialize) serializes apex objects into json content. serialize(objecttoserialize, suppressapexobjectnulls) suppresses null values when serializing apex objects into json content. serializepretty(objecttoserialize) serializes apex objects into json content and generates indented content using the pretty-print format. serializepretty(objecttoserialize, suppressapexobjectnulls) suppresses null values when serializing apex objects into json content and generates indented content using the pretty-print format. creategenerator(prettyprint) returns a new json generator. signature public static system.jsongenerator creategenerator(boolean prettyprint) parameters prettyprint type: boolean determines whether the json generator creates json content in pretty-print format with the content indented. set to true to create indented content. return value type: system.jsongenerator 3074apex reference guide json class createparser(jsonstring) returns a new json parser. signature public static system.jsonparser createparser(string jsonstring) parameters jsonstring type: string the json content to parse. return value type: system.jsonparser deserialize(jsonstring, apextype) deserializes the specified json string into an apex object of the specified type. signature public static object deserialize(string jsonstring, system.type apextype) parameters jsonstring type: string the json content to deserialize. apextype type: system.type the apex type of the object that this method creates after deserializing the json content. 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. 3075apex reference guide json class example the following example deserializes a decimal value. decimal n = (decimal)json.deserialize( '100.1', decimal.class); system.assertequals(n, 100.1); deserializestrict(jsonstring, apextype) deserializes the specified json string into an apex object of the specified type. signature public static object deserializestrict(string jsonstring, system.type apextype) parameters jsonstring type: string the json content to deserialize. apextype type: system.type the apex type of the object that this method creates after deserializing the json content. return value type: object usage all attributes in the json string must be present in the specified type. 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. example the following example deserializes a json string into an object of a user-defined type represented by the car class, which this example also defines. public class car { public string make; public string year; } public void parse() { car c = (car)json.deserializestrict( '{"make":"sfdc","year":"2020"}', car.class); system.assertequals(c.make, 'sfdc'); 3076apex reference guide json class system.assertequals(c.year, '2020'); } deserializeuntyped(jsonstring) deserializes the specified json string into collections of primitive data types. signature public static object deserializeuntyped(string jsonstring) parameters jsonstring type: string the json content to deserialize. return value type: object example the following example deserializes a json representation of an appliance object into a map that contains primitive data types and further collections of primitive types. it then verifies the deserialized values. string jsoninput = '{\n' + ' "description" :"an appliance",\n' + ' "accessories" : [ "powercord", ' + '{ "right":"door handle1", ' + '"left":"door handle2" } ],\n' + ' "dimensions" : ' + '{ "height" : 5.5 , ' + '"width" : 3.0 , ' + '"depth" : 2.2 },\n' + ' "type" : null,\n' + ' "inventory" : 2000,\n' + ' "price" : 1023.45,\n' + ' "isshipped" : true,\n' + ' "modelnumber" : "123"\n' + '}'; map<string, object> m = (map<string, object>) json.deserializeuntyped(jsoninput); system.assertequals( 'an appliance', m.get('description')); list<object> a = (list<object>)m.get('accessories'); system.assertequals('powercord', a[0]); 3077apex reference guide json class map<string, object> a2 = (map<string, object>)a[1]; system.assertequals( 'door handle1', a2.get('right')); system.assertequals( 'door handle2', a2.get('left')); map<string, object> dim = (map<string, object>)m.get('dimensions'); system.assertequals( 5.5, dim.get('height')); system.assertequals( 3.0, dim. |
get('width')); system.assertequals( 2.2, dim.get('depth')); system.assertequals(null, m.get('type')); system.assertequals( 2000, m.get('inventory')); system.assertequals( 1023.45, m.get('price')); system.assertequals( true, m.get('isshipped')); system.assertequals( '123', m.get('modelnumber')); serialize(objecttoserialize) serializes apex objects into json content. signature public static string serialize(object objecttoserialize) parameters objecttoserialize type: object the apex object to serialize. return value type: string example the following example serializes a new datetime value. datetime dt = datetime.newinstance( date.newinstance( 2011, 3, 22), time.newinstance( 3078apex reference guide json class 1, 15, 18, 0)); string str = json.serialize(dt); system.assertequals( '"2011-03-22t08:15:18.000z"', str); serialize(objecttoserialize, suppressapexobjectnulls) suppresses null values when serializing apex objects into json content. signature public static string serialize(object objecttoserialize, boolean suppressapexobjectnulls) parameters objecttoserialize type: object the apex object to serialize. suppressapexobjectnulls type: boolean if true, remove null values before serializing the json object. note: this parameter doesn’t apply to sobjects retrieved via soql. return value type: string usage this method allows you to specify whether to suppress null values when serializing apex objects into json content. serializepretty(objecttoserialize) serializes apex objects into json content and generates indented content using the pretty-print format. signature public static string serializepretty(object objecttoserialize) parameters objecttoserialize type: object the apex object to serialize. 3079apex reference guide jsongenerator class return value type: string serializepretty(objecttoserialize, suppressapexobjectnulls) suppresses null values when serializing apex objects into json content and generates indented content using the pretty-print format. signature public static string serializepretty(object objecttoserialize, boolean suppressapexobjectnulls) parameters objecttoserialize type: object the apex object to serialize. suppressapexobjectnulls type: boolean if true, remove null values before serializing the json object. note: this parameter doesn’t apply to sobjects retrieved via soql. return value type: string jsongenerator class contains methods used to serialize objects into json content using the standard json encoding. namespace system usage the system.jsongenerator class is provided to enable the generation of standard json-encoded content and gives you more control on the structure of the json output. see also: apex developer guide: json generator jsongenerator methods the following are methods for jsongenerator. all are instance methods. 3080apex reference guide jsongenerator class in this section: close() closes the json generator. getasstring() returns the generated json content. isclosed() returns true if the json generator is closed; otherwise, returns false. writeblob(blobvalue) writes the specified blob value as a base64-encoded string. writeblobfield(fieldname, blobvalue) writes a field name and value pair using the specified field name and blob value. writeboolean(blobvalue) writes the specified boolean value. writebooleanfield(fieldname, booleanvalue) writes a field name and value pair using the specified field name and boolean value. writedate(datevalue) writes the specified date value in the iso-8601 format. writedatefield(fieldname, datevalue) writes a field name and value pair using the specified field name and date value. the date value is written in the iso-8601 format. writedatetime(datetimevalue) writes the specified date and time value in the iso-8601 format. writedatetimefield(fieldname, datetimevalue) writes a field name and value pair using the |
specified field name and date and time value. the date and time value is written in the iso-8601 format. writeendarray() writes the ending marker of a json array (']'). writeendobject() writes the ending marker of a json object ('}'). writefieldname(fieldname) writes a field name. writeid(identifier) writes the specified id value. writeidfield(fieldname, identifier) writes a field name and value pair using the specified field name and identifier value. writenull() writes the json null literal value. writenullfield(fieldname) writes a field name and value pair using the specified field name and the json null literal value. writenumber(number) writes the specified decimal value. 3081apex reference guide jsongenerator class writenumber(number) writes the specified double value. writenumber(number) writes the specified integer value. writenumber(number) writes the specified long value. writenumberfield(fieldname, number) writes a field name and value pair using the specified field name and decimal value. writenumberfield(fieldname, number) writes a field name and value pair using the specified field name and double value. writenumberfield(fieldname, number) writes a field name and value pair using the specified field name and integer value. writenumberfield(fieldname, number) writes a field name and value pair using the specified field name and long value. writeobject(anyobject) writes the specified apex object in json format. writeobjectfield(fieldname, value) writes a field name and value pair using the specified field name and apex object. writestartarray() writes the starting marker of a json array ('['). writestartobject() writes the starting marker of a json object ('{'). writestring(stringvalue) writes the specified string value. writestringfield(fieldname, stringvalue) writes a field name and value pair using the specified field name and string value. writetime(timevalue) writes the specified time value in the iso-8601 format. writetimefield(fieldname, timevalue) writes a field name and value pair using the specified field name and time value in the iso-8601 format. close() closes the json generator. signature public void close() return value type: void 3082 |
apex reference guide jsongenerator class usage no more content can be written after the json generator is closed. getasstring() returns the generated json content. signature public string getasstring() return value type: string usage this method closes the json generator if it isn't closed already. isclosed() returns true if the json generator is closed; otherwise, returns false. signature public boolean isclosed() return value type: boolean writeblob(blobvalue) writes the specified blob value as a base64-encoded string. signature public void writeblob(blob blobvalue) parameters blobvalue type: blob return value type: void 3083apex reference guide jsongenerator class writeblobfield(fieldname, blobvalue) writes a field name and value pair using the specified field name and blob value. signature public void writeblobfield(string fieldname, blob blobvalue) parameters fieldname type: string blobvalue type: blob return value type: void writeboolean(blobvalue) writes the specified boolean value. signature public void writeboolean(boolean blobvalue) parameters blobvalue type: boolean return value type: void writebooleanfield(fieldname, booleanvalue) writes a field name and value pair using the specified field name and boolean value. signature public void writebooleanfield(string fieldname, boolean booleanvalue) parameters fieldname type: string booleanvalue type: boolean 3084apex reference guide jsongenerator class return value type: void writedate(datevalue) writes the specified date value in the iso-8601 format. signature public void writedate(date datevalue) parameters datevalue type: date return value type: void writedatefield(fieldname, datevalue) writes a field name and value pair using the specified field name and date value. the date value is written in the iso-8601 format. signature public void writedatefield(string fieldname, date datevalue) parameters fieldname type: string datevalue type: date return value type: void writedatetime(datetimevalue) writes the specified date and time value in the iso-8601 format. signature public void writedatetime(datetime datetimevalue) 3085apex reference guide jsongenerator class parameters datetimevalue type: datetime return value type: void writedatetimefield(fieldname, datetimevalue) writes a field name and value pair using the specified field name and date and time value. the date and time value is written in the iso-8601 format. signature public void writedatetimefield(string fieldname, datetime datetimevalue) parameters fieldname type: string datetimevalue type: datetime return value type: void writeendarray() writes the ending marker of a json array (']'). signature public void writeendarray() return value type: void writeendobject() writes the ending marker of a json object ('}'). signature public void writeendobject() 3086apex reference guide jsongenerator class return value type: void writefieldname(fieldname) writes a field name. signature public void writefieldname(string fieldname) parameters fieldname type: string return value type: void writeid(identifier) writes the specified id value. signature public void writeid(id identifier) parameters identifier type: id return value type: void writeidfield(fieldname, identifier) writes a field name and value pair using the specified field name and identifier value. signature public void writeidfield(string fieldname, id identifier) parameters fieldname type: string 3087apex reference guide jsongenerator class identifier type: id return value type: void writenull() writes the json null literal value. signature public void writenull() return value type: void writenullfield(fieldname) writes a field name and value pair using the specified field name and the json null literal value. signature public void writenullfield(string fieldname) parameters fieldname type: string return value type: void writenumber |
(number) writes the specified decimal value. signature public void writenumber(decimal number) parameters number type: decimal 3088apex reference guide jsongenerator class return value type: void writenumber(number) writes the specified double value. signature public void writenumber(double number) parameters number type: double return value type: void writenumber(number) writes the specified integer value. signature public void writenumber(integer number) parameters number type: integer return value type: void writenumber(number) writes the specified long value. signature public void writenumber(long number) parameters number type: long 3089apex reference guide jsongenerator class return value type: void writenumberfield(fieldname, number) writes a field name and value pair using the specified field name and decimal value. signature public void writenumberfield(string fieldname, decimal number) parameters fieldname type: string number type: decimal return value type: void writenumberfield(fieldname, number) writes a field name and value pair using the specified field name and double value. signature public void writenumberfield(string fieldname, double number) parameters fieldname type: string number type: double return value type: void writenumberfield(fieldname, number) writes a field name and value pair using the specified field name and integer value. signature public void writenumberfield(string fieldname, integer number) 3090apex reference guide jsongenerator class parameters fieldname type: string number type: integer return value type: void writenumberfield(fieldname, number) writes a field name and value pair using the specified field name and long value. signature public void writenumberfield(string fieldname, long number) parameters fieldname type: string number type: long return value type: void writeobject(anyobject) writes the specified apex object in json format. signature public void writeobject(object anyobject) parameters anyobject type: object return value type: void writeobjectfield(fieldname, value) writes a field name and value pair using the specified field name and apex object. 3091apex reference guide jsongenerator class signature public void writeobjectfield(string fieldname, object value) parameters fieldname type: string value type: object return value type: void writestartarray() writes the starting marker of a json array ('['). signature public void writestartarray() return value type: void writestartobject() writes the starting marker of a json object ('{'). signature public void writestartobject() return value type: void writestring(stringvalue) writes the specified string value. signature public void writestring(string stringvalue) parameters stringvalue type: string 3092apex reference guide jsongenerator class return value type: void writestringfield(fieldname, stringvalue) writes a field name and value pair using the specified field name and string value. signature public void writestringfield(string fieldname, string stringvalue) parameters fieldname type: string stringvalue type: string return value type: void writetime(timevalue) writes the specified time value in the iso-8601 format. signature public void writetime(time timevalue) parameters timevalue type: time return value type: void writetimefield(fieldname, timevalue) writes a field name and value pair using the specified field name and time value in the iso-8601 format. signature public void writetimefield(string fieldname, time timevalue) 3093apex reference guide jsonparser class parameters fieldname type: string timevalue type: time return value type: void jsonparser class represents a parser for json-encoded content. namespace system usage use the system.jsonparser methods to parse a response that's returned from a call to an external service that is in json format, such as a json-encoded response of a web service callout. see also: apex developer guide: json parsing jsonparser methods the following are methods for jsonparser. all are instance methods. in |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.