text
stringlengths
73
5.28k
and cardpaymentmethodrequest. available in: salesforce implement these classes in your payment gateway adapter. spring '21 and later 345apex developer guide using salesforce features with apex encryption for tokenized payment methods commercepayments uses salesforce field encryption to securely store gateway token values on customer payment method entities such as digitalwallet, cardpaymentmethod, and alternativepaymentmethod. cardpaymentmethod and digitalwallet contain the gatewaytokenencrypted field, available in api v52.0 and later, and the gatewaytoken field, available in api v48.0 and later. both fields store gateway token values. however, gatewaytokenencrypted uses salesforce classic encryption for custom fields to securely encrypt the token. gatewaytoken doesn't use encryption. to ensure secure tokenization, we recommend using gatewaytokenencrypted on your digitalwallets and cardpaymentmethods. the alternativepaymentmethod object uses a gatewaytoken field for token storage, however, this field is encrypted on alternativepaymentmethods. in api version 52.0 and later, cardpaymentmethods and digitalwallets can’t store values for gatewaytokenencryption and gatewaytoken at the same time on the same record. if you try to assign one while the other exists, salesforce throws an error. your payment gateway adapter uses the paymentmethodtokenizationrequest and paymentmethodtokenizationresponse classes to retrieve a gateway token from the payment gateway, encrypt it in salesforce, and store the value on a payment method entity. let's see how we can configure these classes in our payment gateway adapter. implementing tokenization classes in your gateway adapter the following code is used within your paymentgatewayadapter apex class. gateway tokens are created and encrypted when the gatewayresponse class's processrequest method receives a tokenization request. if the request type is tokenize, gatewayresponse calls the createtokenizeresponse method and passes an instance of the paymentmethodtokenizationrequest class. the passed paymentmethodtokenizationrequest object contains the address and cardpaymentmethod information that the payment gateway needs to manage the tokenization process. for example: global commercepayments.gatewayresponse processrequest(commercepayments.paymentgatewaycontext gatewaycontext) { commercepayments.requesttype requesttype = gatewaycontext.getpaymentrequesttype(); commercepayments.gatewayresponse response; try { if (requesttype == commercepayments.requesttype.tokenize) { response = createtokenizeresponse((commercepayments.paymentmethodtokenizationrequest)gatewaycontext.getpaymentrequest()); } //add other else if statements for different request types as needed. return response; } catch(salesforcevalidationexception e) { commercepayments.gatewayerrorresponse error = new commercepayments.gatewayerrorresponse('400', e.getmessage()); return error; } } configure the createtokenizeresponse method to accept an instance of paymentmethodtokenizationrequest and then build an instance of paymentmethodtokenizationresponse based on the values that it receives from the payment 346
apex developer guide using salesforce features with apex gateway. the tokenizeresponse contains the results of the gateway's tokenization process, and if successful, the tokenized value. in this example, we call the setgatewaytokenencrypted method to set the tokenized value in our tokenization response. public commercepayments.gatewayresponse createtokenizeresponse(commercepayments.paymentmethodtokenizationrequest tokenizerequest) { commercepayments.paymentmethodtokenizationresponse tokenizeresponse = new commercepayments.paymentmethodtokenizationresponse(); tokenizeresponse.setgatewaytokenencrypted(encryptedvalue); tokenizeresponse.setgatewaytokendetails(tokendetails); tokenizeresponse.setgatewayavscode(avscode); tokenizeresponse.setgatewaymessage(gatewaymessage); tokenizeresponse.setgatewayresultcode(resultcode); tokenizeresponse.setgatewayresultcodedescription(resultcodedescription); tokenizeresponse.setsalesforceresultcodeinfo(resultcodeinfo); tokenizeresponse.setgatewaydate(system.now()); return tokenizeresponse; } the setgatewaytokenencrypted method is available in salesforce api v52.0 and later. it uses salesforce classic encryption to set the encrypted token value that you can store in gatewaytokenencrypted on a cardpaymentmethod or digitalwallet, or in gatewaytoken on an alternativepaymentmethod. we recommend using setgatewaytokenencrypted to ensure your tokenized payment method values are encrypted and secure. /** @description method to set gateway token to persist in encrypted text */ global void setgatewaytokenencrypted(string gatewaytokenencrypted) { if (gatewaytokenset) { throwtokenerror(); } this.delegate.setgatewaytokenencrypted(gatewaytokenencrypted); gatewaytokenencryptedset = true; } if the instantiated class already has a gateway token, setgatewaytokenencrypted throws an error. note: while the paymentmethodtokenizationresponse's setgatewaytoken method (available in api v48.0 and later) also returns a payment method token, the tokenized value isn't encrypted. tokenization service api the credit card tokenization process replaces sensitive customer information with a one-time algorithmically generated number, called a token, to use during the payment transaction. salesforce stores the token and then uses that token as a representation of the credit card used for transactions. the token lets you store information about the credit card without actually storing sensitive customer data such as credit card numbers in salesforce. implement our tokenization api to add tokenization capabilities to your payment services. in a typical tokenization process, the payments platform accepts customer payment method data and passes it to a remote token service server on the payment gateway, outside of salesforce. the server provides the tokenized value for storage on the platform. for example, a customer provides a credit card number of 4111 1111 1111 1234. the token server stores this value, associates it with a token of 2537446225198291, and sends that token for storage on the platform. during communication with the merchant, the merchant sends the 2537446225198291 token to the token server. the token server confirms that it matches the customer’s token, and authorizes the merchant to perform the transaction against the customer’s card. 347apex developer guide using salesforce features with apex the commerce payments tokenization api accepts credit card information and uses the external payment gateway configured through the customer's salesforce org to tokenize the card information. it then returns the tokenization representation. the api then saves the token in cardpaymentmethod. call the authorization reversal service by making a post request to the following endpoint. endpoint /commerce/payments/payment-method/tokens/ the tokenization service accepts the following request parameters from payment and related entities. table 7: tokenization service input parameters parameter required details required details of the credit card to be tokenized. cardpaymentmethod: { "cardholdername":"", "expirymonth":"", "expiryyear":"", "startmonth":"", "startyear":"", "cvv":"", "cardnumber":"", "cardcategory":"", "cardtype":"", "nickname":"", "cardholderfirstname":"", "cardholderlastname":"", "email":"", "comments":"" } accountid optional salesforce account id of the card owner. optional address information of the customer who "address":{ owns the credit card payment
method "street":"", being tokenized. "city":"", "state":"", "country":"", "postalcode":"", "companyname":"", } paymentgatewayid required the external payment gateway related to the tokenization server. email optional fraud parameter. ipaddress optional fraud parameter. macaddress optional fraud parameter. phone optional fraud parameter. 348apex developer guide using salesforce features with apex parameter required details additionaldata optional any additional data required by the gateway to tokenize a credit card payment method. sample request and response this sample request provides a customer's credit card information for tokenization. { "cardpaymentmethod": { "cardholdername":"carol smith", "expirymonth": "05", "expiryyear": "2025", "startmonth": "", "startyear": "", "cvv": "000", "cardnumber": "4111111111111111", "cardcategory": "credit", "cardtype": "visa", "nickname": "", "cardholderfirstname": "carol", "cardholderlastname": "smith", "email" : "[email protected]", "comments" : "", "accountid": "000xxxxxxxx" }, "address":{ "street": "128 1st street", "city": "san francisco", "state": "ca", "country": "usa", "postalcode": "94015", "companyname": "salesforce" }, "paymentgatewayid" : "000xxxxxxxx", "email": "" "ipaddress": "", "macaddress": "", "phone": "", "additionaldata":{ //add additional information if needed "key1":"value1", "key2":"value2", "key3":"value3", "key4":"value4", "key5":"value5" } } sample success response 349apex developer guide using salesforce features with apex a successful tokenization response updates the payment method and provides information about the gateway response and any payment gateway logs. { "paymentmethod": { "id": "03or0000000xxxxxxx", "accountid" : "001xx000000xxxxxxx", "status" : "active" }, "gatewayresponse" : { "gatewayresultcode": "00", "gatewayresultcodedescription": "transaction normal", "gatewaydate": "2020-12-08t04:03:20.000z", "gatewayavscode" : "7638788018713617", "gatewaymessage" : "8313990738208498", "salesforceresultcode": "success", "gatewaytokenencrypted" : "sf701252" } "paymentgatewaylogs" : [ { "createddate" : "2020-12-08t04:03:20.000z", "gatewayresultcode" : "00", "id" : "0xtr0000000xxxxxxx", "interactionstatus" : "noop" } ], } alternative payment methods an alternative payment method allows customers to store and represent payment method editions information not represented by another pre-defined payment method such as cardpaymentmethod or digitalwallet. common examples of alternative payment available in: salesforce methods include cashondeliver, klarna, and direct debit. alternative payment methods are available spring '21 and later in api v51.0 and later. create a unique record type for each type of alternative payment method in your org. this way, each of your alternative payment methods can show different picklist values and page layouts based on the method provider and gateway provider’s requirements. for example, you could have one alternative payment method record type for direct debit and a different record type for cash on deliver. we also recommend creating a gtwyproviderpaymentmethodtype for each of your unique alternative payment method record types. alternativepaymentmethod has the private sharing model enabled as default for both internal and external users. only the record owner and users with higher ownership have read, edit, and delete access. example: let's say you wanted to make an alternative payment method for giropay. first, create an alternativepaymentmethod record type. new recordtype /services/data/v51.0/sobjects/recordtype { "name" : "giro pay", "developername
" : "giropay", 350apex developer guide using salesforce features with apex "sobjecttype" : "alternativepaymentmethod" } next, create an alternative payment method record for the alternativepaymentmethod record type. new alternativepaymentmethod /services/data/v51.0/sobjects/alternativepaymentmethod { "processingmode": "external", "status":"active", "gatewaytoken":"mhkdsh0oia3mnwjo9ul", "nickname" : "mygiropay", "recordtypeid" : "{record_type_id}" } you can also create a gateway provider payment method type. new gtwyprovpaymentmethodtype { "paymentgatewayproviderid": "xxxxxxxxxxxxxxx", "paymentmethodtype":"alternativepaymentmethod", "gtwyproviderpaymentmethodtype" : "pm_giro", "developername" : "devname", "masterlabel" : "masterlabel", "recordtypeid" : "{record_type_id}" } process payments process a payment in the payment gateway. editions to access commercepayments api, you need the paymentplatform org permission. available in: salesforce 1. get the payment capture request object from the paymentgatewaycontext class. spring ’20 commercepayments.capturerequest = (commercepayments.capturerequest)gatewaycontext.getpaymentrequest() 2. set the http request object. httprequest req = new httprequest(); req.setheader('content-type', 'application/json'); 3. read the parameters from the capturerequest object and prepare the http request body. 4. make the http call to the gateway using the paymentshttp class. commercepayments.paymentshttp http = new commercepayments.paymentshttp(); httpresponse res = http.send(req); 351apex developer guide using salesforce features with apex 5. parse the httpresponse and prepare the captureresponse object. commercepayments.captureresponse captureresponse = new commercepayments.captureresponse(); captureresponse.setgatewayresultcode(“”); captureresponse.setgatewayresultcodedescription(“”); captureresponse.setgatewayreferencenumber(“”); captureresponse.setsalesforceresultcodeinfo(getsalesforceresultcodeinfo(commercepayments.salesforceresultcode.success.name())); captureresponse.setgatewayreferencedetails(“”); captureresponse.setamount(double.valueof(100); 6. return the captureresponse. process refund process a refund in the payment gateway. editions to access the commercepayments api, you need the paymentplatform org permission. available in: salesforce 1. get the referenced refund request object from the paymentgatewaycontext class. spring ’20 commercepayments.referencedrefundrequest = (commercepayments.referencedrefundrequest)gatewaycontext.getpaymentrequest(); 2. set the http request object. httprequest req = new httprequest(); req.setheader('content-type', 'application/json'); 3. read the parameters from the referencedrefundrequest object and prepare the http request body. 4. make the http call to the gateway using thepaymentshttp class. commercepayments.paymentshttp http = new commercepayments.paymentshttp(); httpresponse res = http.send(req); 5. parse the httpresponse and prepare the referencedrefundresponse object. commercepayments.referencedrefundresponse referencedrefundresponse = new commercepayments.referencedrefundresponse(); referencedrefundresponse.setgatewayresultcode(“”); referencedrefundresponse.setgatewayresultcodedescription(“”); referencedrefundresponse.setgatewayreferencenumber(“”); referencedrefundresponse.setsalesforceresultcodeinfo(getsalesforceresultcodeinfo(commercepayments.salesforceresultcode.success.name())); referencedrefundresponse.setgatewayreferencedetails(“”); referencedrefundresponse.setamount(double.valueof(100); 6. return the referencedrefundresponse. 352apex developer guide using salesforce features with apex idempotency guidelines idempotency represents the ability of a payment gateway to recognize duplicate requests submitted
editions either in error or maliciously, and then process the duplicate requests accordingly. when working with an idempotent gateway, consider these important guidelines. available in: salesforce to access the commercepayments api, you need the paymentplatform org permission. spring ’20 the payment gateway adapter class is linked to a paymentgatewayprovider object record. ccs payments provides its own layer of idempotency for its own service request. each payment gateway can also specify their idempotencysupported value in the paymentgatewayprovider object record. if salesforce ccs payment apis detects a duplicate request and the gateway provider supports idempotency, the request body’s duplicate parameter becomes true. commercepayments.capturerequest request = (commercepayments.capturerequest)paymentgatewaycontext.getpaymentrequest(); boolean isduplicate = requestobject.duplicate the idempotency key can be fetched from the request object. string idempotencykey = request.idempotencykey sample payment gateway implementation for commercepayments we’ve created a github repository containing code samples for a sample payeezy payment gateway implementation with the commercepayments namespace. review the sample code if you need help with configuring your payment gateway implementation. review our code samples in the commercepayments gateway reference implementation for payeezy repository. connect in apex use connect in apex to develop custom experiences in salesforce. connect in apex provides programmatic access to b2b commerce, cms managed content, experience cloud sites, topics, and more. create apex pages that display chatter feeds, post feed items with mentions and topics, and update user and group photos. create triggers that update chatter feeds. many connect rest api resource actions are exposed as static methods on apex classes in the connectapi namespace. these methods use other connectapi classes to input and return information. we refer to the connectapi namespace as connect in apex. in apex, you can access some connect data using soql queries and objects. however, it’s simpler to expose data in connectapi classes, and data is localized and structured for display. for example, instead of making several calls to access and assemble a feed, you can do it with a single call. connect in apex methods execute in the context of the user executing the methods. the code has access to whatever the context user has access to. it doesn’t run in system mode like other apex code. for connect in apex reference information, see connectapi namespace. in this section: connect in apex examples use these examples to perform common tasks with connect in apex. connect in apex features this topic describes which classes and methods to use to work with common connect in apex features. 353apex developer guide using salesforce features with apex using connectapi input and output classes some classes in the connectapi namespace contain static methods that access connect rest api data. the connectapi namespace also contains input classes to pass as parameters and output classes that calls to the static methods return. understanding limits for connectapi classes limits for methods in the connectapi namespace are different than the limits for other apex classes. packaging connectapi classes if you include connectapi classes in a package, be aware of chatter dependencies. serializing and deserializing connectapi objects when connectapi output objects are serialized into json, the structure is similar to the json returned from connect rest api. when connectapi input objects are deserialized from json, the format is also similar to connect rest api. connectapi versioning and equality checking versioning in connectapi classes follows specific rules that are different than the rules for other apex classes. casting connectapi objects it may be useful to downcast some connectapi output objects to a more specific type. wildcards use wildcard characters to match text patterns in connect rest api and connect in apex searches. testing connectapi code like all apex code, connect in apex code requires test coverage. differences between connectapi classes and other apex classes note these additional differences between connectapi classes and other apex classes. connect in apex examples use these examples to perform common tasks with connect in apex. in this section: get feed elements from a feed call a method to get feed elements from a feed. get feed elements from another user’s feed call a method to get feed elements from another user’s feed. get site-specific feed elements from a feed call a method to display a user profile feed that contains only feed elements that are scoped to a specific experience cloud site. post
a feed element make a call to post a feed element. post a feed element with a mention call a method or use the connectapihelper repository to post a feed. post a feed element with existing files call a method to post a feed element with already uploaded files. post a rich-text feed element with inline image call a method or use the connectapihelper repository to post a feed element with an already uploaded, inline image. 354apex developer guide using salesforce features with apex post a rich-text feed element with a code block call a method to post a feed element with a code block. post a feed element with a new file (binary) attachment call a method to post a feed element with a new file. post a batch of feed elements use a trigger to call a method to bulk post to the feeds of accounts. post a batch of feed elements with a new (binary) file use a trigger to call a method to bulk post a new file to the feeds of accounts. define an action link and post with a feed element create one action link in an action link group, associate the action link group with a feed item, and post the feed item. define an action link in a template and post with a feed element create an action link and action link group and instantiate the action link group from a template. edit a feed element call a method to edit a feed element. edit a question title and post call a method to edit a question title and post. like a feed element call a method to like a feed element. bookmark a feed element call a method to bookmark a feed element. share a feed element (prior to version 39.0) call a method to share a feed element. share a feed element (in version 39.0 and later) call a method to share a feed element. send a direct message call a method to send a direct message. post a comment call a method to post a comment. post a comment with a mention make call or use the connectapihelper repository to post a comment with a mention. post a comment with an existing file make a call to post a comment with an already uploaded file. post a comment with a new file call a method to post a comment with a new file. post a rich-text comment with inline image make a call or use the connectapihelper repository to post a comment with an already uploaded, inline image. post a rich-text feed comment with a code block call a method to post a comment with a code block. edit a comment call a method to edit a comment. 355apex developer guide using salesforce features with apex follow a record call a method to follow a record. unfollow a record call a method to stop following a record. get a repository call a method to get a repository. get repositories call a method to get all repositories. get allowed item types call a method to get allowed item types. get previews call a method to get all supported preview formats and their respective urls. get a file preview call a method to get a file preview. get repository folder items call a method to get a collection of repository folder items. get a repository folder call a method to get a repository folder. get a repository file without permissions information call a method to get a repository file without permission information. get a repository file with permissions information call a method to get a repository file with permission information. create a repository file without content (metadata only) call a method to create a file without binary content (metadata only) in a google drive repository folder. create a repository file with content call a method to create a file with binary content in a google drive repository folder. update a repository file without content (metadata only) call a method to update the metadata of a repository file. update a repository file with content call a method to update a repository file with content. get an authentication url call a method to get an authentication url. get feed elements from a feed call a method to get feed elements from a feed. call getfeedelementsfromfeed(communityid, feedtype, subjectid) to get the first page of feed elements from the context user’s news feed. connectapi.feedelementpage fep = connectapi.chatterfeeds.getfeedelementsfromfeed(network.getnetworkid(), connectapi.feedtype.news, 'me'); 356apex developer guide using salesforce features with apex the get
feedelementsfromfeed method is overloaded, which means that the method name has many different signatures. a signature is the name of the method and its parameters in order. each signature lets you send different inputs. for example, one signature may specify the feed type and the subject id. another signature could have those parameters and an additional parameter to specify the maximum number of comments to return for each feed element. tip: each signature operates on certain feed types. use the signatures that operate on the connectapi.feedtype.record to get group feeds, since a group is a record type. see also: apex reference guide: chatterfeeds class get feed elements from another user’s feed call a method to get feed elements from another user’s feed. call getfeedelementsfromfeed(communityid, feedtype, subjectid) to get the first page of feed elements from another user’s feed. connectapi.feedelementpage fep = connectapi.chatterfeeds.getfeedelementsfromfeed(network.getnetworkid(), connectapi.feedtype.userprofile, '005r0000000hwma'); this example calls the same method to get the first page of feed elements from another user’s record feed. connectapi.feedelementpage fep = connectapi.chatterfeeds.getfeedelementsfromfeed(network.getnetworkid(), connectapi.feedtype.record, '005r0000000hwma'); the getfeedelementsfromfeed method is overloaded, which means that the method name has many different signatures. a signature is the name of the method and its parameters in order. each signature lets you send different inputs. for example, one signature can specify the feed type and the subject id. another signature could have those parameters and an extra parameter to specify the maximum number of comments to return for each feed element. get site-specific feed elements from a feed call a method to display a user profile feed that contains only feed elements that are scoped to a specific experience cloud site. feed elements that have a user or a group parent record are scoped to sites. feed elements whose parents are record types other than user or group are always visible in all sites. other parent record types could be scoped to sites in the future. this example calls getfeedelementsfromfeed(communityid, feedtype, subjectid, recentcommentcount, density, pageparam, pagesize, sortparam, filter) to get only site-specific feed elements. connectapi.feedelementpage fep = connectapi.chatterfeeds.getfeedelementsfromfeed(network.getnetworkid(), connectapi.feedtype.userprofile, 'me', 3, connectapi.feeddensity.fewerupdates, null, null, connectapi.feedsortorder.lastmodifieddatedesc, connectapi.feedfilter.communityscoped); post a feed element make a call to post a feed element. 357apex developer guide using salesforce features with apex call postfeedelement(communityid, subjectid, feedelementtype, text) to post a string of text. connectapi.feedelement feedelement = connectapi.chatterfeeds.postfeedelement(network.getnetworkid(), '0f9d0000000treh', connectapi.feedelementtype.feeditem, 'on vacation this week.'); the second parameter, subjectid is the id of the parent this feed element is posted to. the value can be the id of a user, group, or record, or the string me to indicate the context user. post a feed element with a mention call a method or use the connectapihelper repository to post a feed. you can post feed elements with mentions two ways. use the connectapihelper repository on github to write a single line of code, or use this example, which calls postfeedelement(communityid, feedelement). connectapi.feediteminput feediteminput = new connectapi.feediteminput(); connectapi.mentionsegmentinput mentionsegmentinput = new connectapi.mentionsegmentinput(); connectapi.messagebodyinput messagebodyinput = new connectapi.messagebodyinput(); connectapi.textsegmentinput textsegmentinput = new connectapi.textsegmentinput(); messagebodyinput.messagesegments = new list<connectapi.messagesegmentinput>(); mentionsegmentinput.id = '005rr000000dme9'; messagebodyinput.messagesegments.add(mentionsegmentinput);
textsegmentinput.text = 'could you take a look?'; messagebodyinput.messagesegments.add(textsegmentinput); feediteminput.body = messagebodyinput; feediteminput.feedelementtype = connectapi.feedelementtype.feeditem; feediteminput.subjectid = '0f9rr0000004cpw'; connectapi.feedelement feedelement = connectapi.chatterfeeds.postfeedelement(network.getnetworkid(), feediteminput); post a feed element with existing files call a method to post a feed element with already uploaded files. call postfeedelement(communityid, feedelement) to post a feed item with files that have already been uploaded. // define the feediteminput object to pass to postfeedelement connectapi.feediteminput feediteminput = new connectapi.feediteminput(); feediteminput.subjectid = 'me'; connectapi.textsegmentinput textsegmentinput = new connectapi.textsegmentinput(); textsegmentinput.text = 'would you please review these docs?'; // the messagebodyinput object holds the text in the post connectapi.messagebodyinput messagebodyinput = new connectapi.messagebodyinput(); messagebodyinput.messagesegments = new list<connectapi.messagesegmentinput>(); messagebodyinput.messagesegments.add(textsegmentinput); feediteminput.body = messagebodyinput; // the feedelementcapabilitiesinput object holds the capabilities of the feed item. 358apex developer guide using salesforce features with apex // for this feed item, we define a files capability to hold the file(s). list<string> fileids = new list<string>(); fileids.add('069xx00000000qo'); fileids.add('069xx00000000qt'); fileids.add('069xx00000000qn'); fileids.add('069xx00000000qi'); fileids.add('069xx00000000qd'); connectapi.filescapabilityinput filesinput = new connectapi.filescapabilityinput(); filesinput.items = new list<connectapi.fileidinput>(); for (string fileid : fileids) { connectapi.fileidinput idinput = new connectapi.fileidinput(); idinput.id = fileid; filesinput.items.add(idinput); } connectapi.feedelementcapabilitiesinput feedelementcapabilitiesinput = new connectapi.feedelementcapabilitiesinput(); feedelementcapabilitiesinput.files = filesinput; feediteminput.capabilities = feedelementcapabilitiesinput; // post the feed item. connectapi.feedelement feedelement = connectapi.chatterfeeds.postfeedelement(network.getnetworkid(), feediteminput); post a rich-text feed element with inline image call a method or use the connectapihelper repository to post a feed element with an already uploaded, inline image. you can post rich-text feed elements with inline images and mentions two ways. use the connectapihelper repository on github to write a single line of code, or use this example, which calls postfeedelement(communityid, feedelement). in this example, the image file is existing content that has already been uploaded to salesforce. the post also includes text and a mention. string communityid = null; string imageid = '069d00000001ina'; string mentioneduserid = '005d0000001qnpr'; string targetuserorgrouporrecordid = '005d0000001gif0'; connectapi.feediteminput input = new connectapi.feediteminput(); input.subjectid = targetuserorgrouporrecordid; input.feedelementtype = connectapi.feedelementtype.feeditem; connectapi.messagebodyinput messageinput = new connectapi.messagebodyinput(); connectapi.textsegmentinput textsegment; connectapi.mentionsegmentinput mentionsegment; connectapi.markupbeginsegmentinput markupbeginsegment; connectapi.markupendsegmentinput markupendsegment; connectapi.inlineimagesegmentinput inlineimagesegment; messageinput.messagesegments = new list<connectapi.messagesegmentinput>(); markupbeginsegment = new connectapi.markupbeginsegmentinput(); 359apex developer guide using salesforce features
with apex markupbeginsegment.markuptype = connectapi.markuptype.bold; messageinput.messagesegments.add(markupbeginsegment); textsegment = new connectapi.textsegmentinput(); textsegment.text = 'hello '; messageinput.messagesegments.add(textsegment); mentionsegment = new connectapi.mentionsegmentinput(); mentionsegment.id = mentioneduserid; messageinput.messagesegments.add(mentionsegment); textsegment = new connectapi.textsegmentinput(); textsegment.text = '!'; messageinput.messagesegments.add(textsegment); markupendsegment = new connectapi.markupendsegmentinput(); markupendsegment.markuptype = connectapi.markuptype.bold; messageinput.messagesegments.add(markupendsegment); inlineimagesegment = new connectapi.inlineimagesegmentinput(); inlineimagesegment.alttext = 'image one'; inlineimagesegment.fileid = imageid; messageinput.messagesegments.add(inlineimagesegment); input.body = messageinput; connectapi.chatterfeeds.postfeedelement(communityid, input); see also: apex reference guide: connectapi.markupbeginsegmentinput apex reference guide: connectapi.markupendsegmentinput apex reference guide: connectapi.inlineimagesegmentinput post a rich-text feed element with a code block call a method to post a feed element with a code block. call postfeedelement(communityid, feedelement) to post a feed item with a code block. string communityid = null; string targetuserorgrouporrecordid = 'me'; string codesnippet = '<html>\n\t<body>\n\t\thello, world!\n\t</body>\n</html>'; connectapi.feediteminput input = new connectapi.feediteminput(); input.subjectid = targetuserorgrouporrecordid; input.feedelementtype = connectapi.feedelementtype.feeditem; connectapi.messagebodyinput messageinput = new connectapi.messagebodyinput(); connectapi.textsegmentinput textsegment; connectapi.markupbeginsegmentinput markupbeginsegment; connectapi.markupendsegmentinput markupendsegment; messageinput.messagesegments = new list<connectapi.messagesegmentinput>(); 360apex developer guide using salesforce features with apex markupbeginsegment = new connectapi.markupbeginsegmentinput(); markupbeginsegment.markuptype = connectapi.markuptype.code; messageinput.messagesegments.add(markupbeginsegment); textsegment = new connectapi.textsegmentinput(); textsegment.text = codesnippet; messageinput.messagesegments.add(textsegment); markupendsegment = new connectapi.markupendsegmentinput(); markupendsegment.markuptype = connectapi.markuptype.code; messageinput.messagesegments.add(markupendsegment); input.body = messageinput; connectapi.chatterfeeds.postfeedelement(communityid, input); see also: apex reference guide: connectapi.markupbeginsegmentinput apex reference guide: connectapi.markupendsegmentinput post a feed element with a new file (binary) attachment call a method to post a feed element with a new file. important: in version 36.0 and later, you can’t post a feed element with a new file in the same call. upload files to salesforce first, and then specify existing files when posting a feed element. this example calls postfeedelement(communityid, feedelement, feedelementfileupload) to post a feed item with a new file (binary) attachment. connectapi.feediteminput input = new connectapi.feediteminput(); input.subjectid = 'me'; connectapi.contentcapabilityinput contentinput = new connectapi.contentcapabilityinput(); contentinput.title = 'title'; connectapi.feedelementcapabilitiesinput capabilities = new connectapi.feedelementcapabilities
input(); capabilities.content = contentinput; input.capabilities = capabilities; string text = 'these are the contents of the new file.'; blob myblob = blob.valueof(text); connectapi.binaryinput bininput = new connectapi.binaryinput(myblob, 'text/plain', 'filename'); connectapi.chatterfeeds.postfeedelement(network.getnetworkid(), input, bininput); post a batch of feed elements use a trigger to call a method to bulk post to the feeds of accounts. 361apex developer guide using salesforce features with apex this trigger calls postfeedelementbatch(communityid, feedelements) to bulk post to the feeds of newly inserted accounts. trigger postfeeditemtoaccount on account (after insert) { account[] accounts = trigger.new; // bulk post to the account feeds. list<connectapi.batchinput> batchinputs = new list<connectapi.batchinput>(); for (account a : accounts) { connectapi.feediteminput input = new connectapi.feediteminput(); input.subjectid = a.id; connectapi.messagebodyinput body = new connectapi.messagebodyinput(); body.messagesegments = new list<connectapi.messagesegmentinput>(); connectapi.textsegmentinput textsegment = new connectapi.textsegmentinput(); textsegment.text = 'let\'s win the ' + a.name + ' account.'; body.messagesegments.add(textsegment); input.body = body; connectapi.batchinput batchinput = new connectapi.batchinput(input); batchinputs.add(batchinput); } connectapi.chatterfeeds.postfeedelementbatch(network.getnetworkid(), batchinputs); } post a batch of feed elements with a new (binary) file use a trigger to call a method to bulk post a new file to the feeds of accounts. important: this example is valid in version 32.0–35.0. in version 36.0 and later, you can’t post a batch of feed elements with a new file in the same call. upload the file to salesforce first, and then specify the uploaded file when posting a batch of feed elements. this trigger calls postfeedelementbatch(communityid, feedelements) to bulk post to the feeds of newly inserted accounts. each post has a new file (binary) attachment. trigger postfeeditemtoaccountwithbinary on account (after insert) { account[] accounts = trigger.new; // bulk post to the account feeds. list<connectapi.batchinput> batchinputs = new list<connectapi.batchinput>(); for (account a : accounts) { connectapi.feediteminput input = new connectapi.feediteminput(); input.subjectid = a.id; connectapi.messagebodyinput body = new connectapi.messagebodyinput(); body.messagesegments = new list<connectapi.messagesegmentinput>(); 362apex developer guide using salesforce features with apex connectapi.textsegmentinput textsegment = new connectapi.textsegmentinput(); textsegment.text = 'let\'s win the ' + a.name + ' account.'; body.messagesegments.add(textsegment); input.body = body; connectapi.contentcapabilityinput contentinput = new connectapi.contentcapabilityinput(); contentinput.title = 'title'; connectapi.feedelementcapabilitiesinput capabilities = new connectapi.feedelementcapabilitiesinput(); capabilities.content = contentinput; input.capabilities = capabilities; string text = 'we are words in a file.'; blob myblob = blob.valueof(text); connectapi.binaryinput bininput = new connectapi.binaryinput(myblob, 'text/plain', 'filename'); connectapi.batchinput batchinput = new connectapi.batchinput(input, bininput); batchinputs.add(batchinput); } connectapi.chatterfeeds.postfeedelementbatch(network.getnetworkid(), batchinputs); define an action link and post with a feed element create one action link in an action link group, associate
the action link group with a feed item, and post the feed item. 363apex developer guide using salesforce features with apex when a user clicks the action link, the action link requests the connect rest api resource /chatter/feed-elements, which posts a feed item to the user’s feed. after the user clicks the action link and it executes successfully, its status changes to successful and the feed item ui is updated. 364apex developer guide using salesforce features with apex refresh the user’s feed to see the new post. this simple example shows you how to use action links to call a salesforce resource. think of an action link as a button on a feed item. like a button, an action link definition includes a label (labelkey). an action link group definition also includes other properties like a url (actionurl), an http method (method), and an optional request body (requestbody) and http headers (headers). when a user clicks this action link, an http post request is made to a connect rest api resource, which posts a feed item to chatter. the requestbody property holds the request body for the actionurl resource, including the text of the new feed item. in this example, the new feed item includes only text, but it could include other capabilities such as a file attachment, a poll, or even action links. just like radio buttons, action links must be nested in a group. action links within a group share the properties of the group and are mutually exclusive (you can click only one action link within a group). even if you define only one action link, it must be part of an action link group. this example calls connectapi.actionlinks.createactionlinkgroupdefinition(communityid, actionlinkgroup) to create an action link group definition. it saves the action link group id from that call and associates it with a feed element in a call to connectapi.chatterfeeds.postfeedelement(communityid, feedelement). to use this code, substitute an oauth value for your own salesforce org. also, verify that the expirationdate is in the future. look for the “to do” comments in the code. connectapi.actionlinkgroupdefinitioninput actionlinkgroupdefinitioninput = new connectapi.actionlinkgroupdefinitioninput(); connectapi.actionlinkdefinitioninput actionlinkdefinitioninput = new connectapi.actionlinkdefinitioninput(); connectapi.requestheaderinput requestheaderinput1 = new connectapi.requestheaderinput(); 365apex developer guide using salesforce features with apex connectapi.requestheaderinput requestheaderinput2 = new connectapi.requestheaderinput(); // create the action link group definition. actionlinkgroupdefinitioninput.actionlinks = new list<connectapi.actionlinkdefinitioninput>(); actionlinkgroupdefinitioninput.executionsallowed = connectapi.actionlinkexecutionsallowed.onceperuser; actionlinkgroupdefinitioninput.category = connectapi.platformactiongroupcategory.primary; // to do: verify that the date is in the future. // action link groups are removed from feed elements on the expiration date. datetime mydate = datetime.newinstance(2016, 3, 1); actionlinkgroupdefinitioninput.expirationdate = mydate; // create the action link definition. actionlinkdefinitioninput.actiontype = connectapi.actionlinktype.api; actionlinkdefinitioninput.actionurl = '/services/data/v33.0/chatter/feed-elements'; actionlinkdefinitioninput.headers = new list<connectapi.requestheaderinput>(); actionlinkdefinitioninput.labelkey = 'post'; actionlinkdefinitioninput.method = connectapi.httprequestmethod.httppost; actionlinkdefinitioninput.requestbody = '{\"subjectid\": \"me\",\"feedelementtype\": \"feeditem\",\"body\": {\"messagesegments\": [{\"type\": \"text\",\"text\": \"this is a test post created via an api action link.\"}]}}'; actionlinkdefinitioninput.requiresconfirmation = true; // to do: substitute an oauth value for your salesforce org. requestheaderinput1.name = 'authorization'; requestheaderinput1.value = 'oauth 00dd00000007wnp!arsaqcwoev0zzav847ftl4zf.85w.ewspbugxr4sajsp'; actionlinkdefinitioninput.headers.add(requestheaderinput1); requestheaderinput2.name = 'content
-type'; requestheaderinput2.value = 'application/json'; actionlinkdefinitioninput.headers.add(requestheaderinput2); // add the action link definition to the action link group definition. actionlinkgroupdefinitioninput.actionlinks.add(actionlinkdefinitioninput); // instantiate the action link group definition. connectapi.actionlinkgroupdefinition actionlinkgroupdefinition = connectapi.actionlinks.createactionlinkgroupdefinition(network.getnetworkid(), actionlinkgroupdefinitioninput); connectapi.feediteminput feediteminput = new connectapi.feediteminput(); connectapi.feedelementcapabilitiesinput feedelementcapabilitiesinput = new connectapi.feedelementcapabilitiesinput(); connectapi.associatedactionscapabilityinput associatedactionscapabilityinput = new connectapi.associatedactionscapabilityinput(); connectapi.messagebodyinput messagebodyinput = new connectapi.messagebodyinput(); connectapi.textsegmentinput textsegmentinput = new connectapi.textsegmentinput(); // set the properties of the feediteminput object. feediteminput.body = messagebodyinput; feediteminput.capabilities = feedelementcapabilitiesinput; feediteminput.subjectid = 'me'; 366apex developer guide using salesforce features with apex // create the text for the post. messagebodyinput.messagesegments = new list<connectapi.messagesegmentinput>(); textsegmentinput.text = 'click to post a feed item.'; messagebodyinput.messagesegments.add(textsegmentinput); // the feedelementcapabilitiesinput object holds the capabilities of the feed item. // define an associated actions capability to hold the action link group. // the action link group id is returned from the call to create the action link group definition. feedelementcapabilitiesinput.associatedactions = associatedactionscapabilityinput; associatedactionscapabilityinput.actionlinkgroupids = new list<string>(); associatedactionscapabilityinput.actionlinkgroupids.add(actionlinkgroupdefinition.id); // post the feed item. connectapi.feedelement feedelement = connectapi.chatterfeeds.postfeedelement(network.getnetworkid(), feediteminput); note: if the post fails, check the oauth id. define an action link in a template and post with a feed element create an action link and action link group and instantiate the action link group from a template. this example creates the same action link and action link group as the example define an action link and post with a feed element, but this example instantiates the action link group from a template. step 1: create the action link templates 1. from setup, enter action link templates in the quick find box, then select action link templates. 2. use these values in a new action link group template: field value name doc example developer name doc_example category primary action executions allowed once per user 3. use these values in a new action link template: field value action link group template doc example action type api action url /services/data/{!bindings.apiversion}/chatter/feed-elements 367apex developer guide using salesforce features with apex field value user visibility everyone can see http request body { "subjectid":"{!bindings.subjectid}", "feedelementtype":"feeditem", "body":{ "messagesegments":[ { "type":"text", "text":"{!bindings.text}" } ] } } http headers content-type: application/json position 0 label key post http method post 4. go back to the action link group template and select published. click save. step 2: instantiate the action link group, associate it with a feed item, and post it this example calls connectapi.actionlinks.createactionlinkgroupdefinition(communityid, actionlinkgroup) to create an action link group definition. it calls connectapi.chatterfeeds.postfeedelement(communityid, feedelement) to associate the action link group with a feed item and post it. // get the action link group template id. actionlinkgrouptemplate template = [select id from actionlinkgrouptemplate where developername='doc_example']; // add binding name-value pairs to a map. // the names are defined in the action link template(s) associated with the action link group template. // get them from setup ui or soql
. map<string, string> bindingmap = new map<string, string>(); bindingmap.put('apiversion', 'v33.0'); bindingmap.put('text', 'this post was created by an api action link.'); bindingmap.put('subjectid', 'me'); // create actionlinktemplatebindinginput objects from the map elements. list<connectapi.actionlinktemplatebindinginput> bindinginputs = new list<connectapi.actionlinktemplatebindinginput>(); for (string key : bindingmap.keyset()) { connectapi.actionlinktemplatebindinginput bindinginput = new connectapi.actionlinktemplatebindinginput(); bindinginput.key = key; bindinginput.value = bindingmap.get(key); bindinginputs.add(bindinginput); } // set the template id and template binding values in the action link group definition. connectapi.actionlinkgroupdefinitioninput actionlinkgroupdefinitioninput = new connectapi.actionlinkgroupdefinitioninput(); 368apex developer guide using salesforce features with apex actionlinkgroupdefinitioninput.templateid = template.id; actionlinkgroupdefinitioninput.templatebindings = bindinginputs; // instantiate the action link group definition. connectapi.actionlinkgroupdefinition actionlinkgroupdefinition = connectapi.actionlinks.createactionlinkgroupdefinition(network.getnetworkid(), actionlinkgroupdefinitioninput); connectapi.feediteminput feediteminput = new connectapi.feediteminput(); connectapi.feedelementcapabilitiesinput feedelementcapabilitiesinput = new connectapi.feedelementcapabilitiesinput(); connectapi.associatedactionscapabilityinput associatedactionscapabilityinput = new connectapi.associatedactionscapabilityinput(); connectapi.messagebodyinput messagebodyinput = new connectapi.messagebodyinput(); connectapi.textsegmentinput textsegmentinput = new connectapi.textsegmentinput(); // define the feediteminput object to pass to postfeedelement feediteminput.body = messagebodyinput; feediteminput.capabilities = feedelementcapabilitiesinput; feediteminput.subjectid = 'me'; // the messagebodyinput object holds the text in the post messagebodyinput.messagesegments = new list<connectapi.messagesegmentinput>(); textsegmentinput.text = 'click to post a feed item.'; messagebodyinput.messagesegments.add(textsegmentinput); // the feedelementcapabilitiesinput object holds the capabilities of the feed item. // for this feed item, we define an associated actions capability to hold the action link group. // the action link group id is returned from the call to create the action link group definition. feedelementcapabilitiesinput.associatedactions = associatedactionscapabilityinput; associatedactionscapabilityinput.actionlinkgroupids = new list<string>(); associatedactionscapabilityinput.actionlinkgroupids.add(actionlinkgroupdefinition.id); // post the feed item. connectapi.feedelement feedelement = connectapi.chatterfeeds.postfeedelement(network.getnetworkid(), feediteminput); edit a feed element call a method to edit a feed element. call updatefeedelement(communityid, feedelementid, feedelement) to edit a feed element. feed items are the only type of feed element that can be edited. string communityid = network.getnetworkid(); // get the last feed item created by the context user. list<feeditem> feeditems = [select id from feeditem where createdbyid = :userinfo.getuserid() order by createddate desc]; if (feeditems.isempty()) { 369apex developer guide using salesforce features with apex // return null within anonymous apex. return null; } string feedelementid = feeditems[0].id; connectapi.feedentityiseditable iseditable = connectapi.chatterfeeds.isfeedelementeditablebyme(communityid, feedelementid); if (iseditable.iseditablebyme == true){ connectapi.feediteminput feediteminput = new connectapi.feediteminput(); connectapi.messagebodyinput messagebodyinput = new connectapi.messagebodyinput(); connectapi.textsegmentinput textsegmentinput = new connectapi.textsegmentinput(); messagebodyinput.messagesegments = new list<
connectapi.messagesegmentinput>(); textsegmentinput.text = 'this is my edited post.'; messagebodyinput.messagesegments.add(textsegmentinput); feediteminput.body = messagebodyinput; connectapi.feedelement editedfeedelement = connectapi.chatterfeeds.updatefeedelement(communityid, feedelementid, feediteminput); } edit a question title and post call a method to edit a question title and post. call updatefeedelement(communityid, feedelementid, feedelement) to edit a question title and post. string communityid = network.getnetworkid(); // get the last feed item created by the context user. list<feeditem> feeditems = [select id from feeditem where createdbyid = :userinfo.getuserid() order by createddate desc]; if (feeditems.isempty()) { // return null within anonymous apex. return null; } string feedelementid = feeditems[0].id; connectapi.feedentityiseditable iseditable = connectapi.chatterfeeds.isfeedelementeditablebyme(communityid, feedelementid); if (iseditable.iseditablebyme == true){ connectapi.feediteminput feediteminput = new connectapi.feediteminput(); connectapi.feedelementcapabilitiesinput feedelementcapabilitiesinput = new connectapi.feedelementcapabilitiesinput(); connectapi.questionandanswerscapabilityinput questionandanswerscapabilityinput = new connectapi.questionandanswerscapabilityinput(); connectapi.messagebodyinput messagebodyinput = new connectapi.messagebodyinput(); connectapi.textsegmentinput textsegmentinput = new connectapi.textsegmentinput(); messagebodyinput.messagesegments = new list<connectapi.messagesegmentinput>(); 370apex developer guide using salesforce features with apex textsegmentinput.text = 'this is my edited question.'; messagebodyinput.messagesegments.add(textsegmentinput); feediteminput.body = messagebodyinput; feediteminput.capabilities = feedelementcapabilitiesinput; feedelementcapabilitiesinput.questionandanswers = questionandanswerscapabilityinput; questionandanswerscapabilityinput.questiontitle = 'where is my edited question?'; connectapi.feedelement editedfeedelement = connectapi.chatterfeeds.updatefeedelement(communityid, feedelementid, feediteminput); } like a feed element call a method to like a feed element. call likefeedelement(communityid, feedelementid) to like a feed element. connectapi.chatterlike chatterlike = connectapi.chatterfeeds.likefeedelement(null, '0d5d0000000kugh'); bookmark a feed element call a method to bookmark a feed element. call updatefeedelementbookmarks(communityid, feedelementid, isbookmarkedbycurrentuser) to bookmark a feed element. connectapi.bookmarkscapability bookmark = connectapi.chatterfeeds.updatefeedelementbookmarks(null, '0d5d0000000kugh', true); share a feed element (prior to version 39.0) call a method to share a feed element. important: in api version 39.0 and later, sharefeedelement(communityid, subjectid, feedelementtype, originalfeedelementid) isn’t supported. see share a feed element (in version 39.0 and later). call sharefeedelement(communityid, subjectid, feedelementtype, originalfeedelementid) to share a feed item (which is a type of feed element) with a group. connectapi.chatterlike chatterlike = connectapi.chatterfeeds.likefeedelement(null, '0d5d0000000kugh'); share a feed element (in version 39.0 and later) call a method to share a feed element. call postfeedelement(communityid, feedelement) to share a feed element. // define the feediteminput object to pass to postfeedelement connectapi.feediteminput feediteminput = new connectapi.feediteminput(); feediteminput.subjectid = 'me'; 371apex developer guide using salesforce features with apex connectapi.textsegmentinput textsegmentinput = new connectapi.textsegmentinput(); textsegmentinput.text =
'look at this post i'm sharing.'; // the messagebodyinput object holds the text in the post connectapi.messagebodyinput messagebodyinput = new connectapi.messagebodyinput(); messagebodyinput.messagesegments = new list<connectapi.messagesegmentinput>(); messagebodyinput.messagesegments.add(textsegmentinput); feediteminput.body = messagebodyinput; connectapi.feedentitysharecapabilityinput shareinput = new connectapi.feedentitysharecapabilityinput(); shareinput.feedentityid = '0d5r0000000sebc'; connectapi.feedelementcapabilitiesinput feedelementcapabilitiesinput = new connectapi.feedelementcapabilitiesinput(); feedelementcapabilitiesinput.feedentityshare = shareinput; feediteminput.capabilities = feedelementcapabilitiesinput; // post the feed item. connectapi.feedelement feedelement = connectapi.chatterfeeds.postfeedelement(network.getnetworkid(), feediteminput); send a direct message call a method to send a direct message. call postfeedelement(communityid, feedelement) to send a direct message to two people. // define the feediteminput object to pass to postfeedelement connectapi.feediteminput feediteminput = new connectapi.feediteminput(); connectapi.textsegmentinput textsegmentinput = new connectapi.textsegmentinput(); textsegmentinput.text = 'thanks for attending my presentation test run this morning. send me any feedback.'; // the messagebodyinput object holds the text in the post connectapi.messagebodyinput messagebodyinput = new connectapi.messagebodyinput(); messagebodyinput.messagesegments = new list<connectapi.messagesegmentinput>(); messagebodyinput.messagesegments.add(textsegmentinput); feediteminput.body = messagebodyinput; // the feedelementcapabilitiesinput object holds the capabilities of the feed item. // for this feed item, we define a direct message capability to hold the member(s) and the subject. list<string> memberids = new list<string>(); memberids.add('005b00000016ouq'); memberids.add('005b0000001rin6'); connectapi.directmessagecapabilityinput dminput = new connectapi.directmessagecapabilityinput(); dminput.subject = 'thank you!'; dminput.memberstoadd = memberids; connectapi.feedelementcapabilitiesinput feedelementcapabilitiesinput = new connectapi.feedelementcapabilitiesinput(); feedelementcapabilitiesinput.directmessage = dminput; 372apex developer guide using salesforce features with apex feediteminput.capabilities = feedelementcapabilitiesinput; // post the feed item. connectapi.feedelement feedelement = connectapi.chatterfeeds.postfeedelement(network.getnetworkid(), feediteminput); post a comment call a method to post a comment. call postcommenttofeedelement(communityid, feedelementid, text) to post a plain text comment to a feed element. connectapi.comment comment = connectapi.chatterfeeds.postcommenttofeedelement(null, '0d5d0000000kugh', 'i agree with the proposal.' ); post a comment with a mention make call or use the connectapihelper repository to post a comment with a mention. you can post comments with mentions two ways. use the connectapihelper repository on github to write a single line of code, or use this example, which calls postcommenttofeedelement(communityid, feedelementid, comment, feedelementfileupload). string communityid = null; string feedelementid = '0d5d0000000ktw3'; connectapi.commentinput commentinput = new connectapi.commentinput(); connectapi.mentionsegmentinput mentionsegmentinput = new connectapi.mentionsegmentinput(); connectapi.messagebodyinput messagebodyinput = new connectapi.messagebodyinput(); connectapi.textsegmentinput textsegmentinput = new connectapi.textsegmentinput(); messagebodyinput.messagesegments = new list<connectapi.messagesegmentinput>(); textsegmentinput.text = 'does anyone in this group have an idea? '; messagebodyinput.messagesegments.add(textsegmentinput); ment
ionsegmentinput.id = '005d00000000oot'; messagebodyinput.messagesegments.add(mentionsegmentinput); commentinput.body = messagebodyinput; connectapi.comment commentrep = connectapi.chatterfeeds.postcommenttofeedelement(communityid, feedelementid, commentinput, null); post a comment with an existing file make a call to post a comment with an already uploaded file. 373apex developer guide using salesforce features with apex to post a comment and attach an existing file (already uploaded to salesforce) to the comment, create a connectapi.commentinput object to pass to postcommenttofeedelement(communityid, feedelementid, comment, feedelementfileupload). string feedelementid = '0d5d0000000ktw3'; connectapi.commentinput commentinput = new connectapi.commentinput(); connectapi.messagebodyinput messagebodyinput = new connectapi.messagebodyinput(); connectapi.textsegmentinput textsegmentinput = new connectapi.textsegmentinput(); textsegmentinput.text = 'i attached this file from salesforce files.'; messagebodyinput.messagesegments = new list<connectapi.messagesegmentinput>(); messagebodyinput.messagesegments.add(textsegmentinput); commentinput.body = messagebodyinput; connectapi.commentcapabilitiesinput commentcapabilitiesinput = new connectapi.commentcapabilitiesinput(); connectapi.contentcapabilityinput contentcapabilityinput = new connectapi.contentcapabilityinput(); commentcapabilitiesinput.content = contentcapabilityinput; contentcapabilityinput.contentdocumentid = '069d00000001rnj'; commentinput.capabilities = commentcapabilitiesinput; connectapi.comment commentrep = connectapi.chatterfeeds.postcommenttofeedelement(network.getnetworkid(), feedelementid, commentinput, null); post a comment with a new file call a method to post a comment with a new file. to post a comment and upload and attach a new file to the comment, create a connectapi.commentinput object and a connectapi.binaryinput object to pass to the postcommenttofeedelement(communityid, feedelementid, comment, feedelementfileupload) method. string feedelementid = '0d5d0000000ktw3'; connectapi.commentinput commentinput = new connectapi.commentinput(); connectapi.messagebodyinput messagebodyinput = new connectapi.messagebodyinput(); connectapi.textsegmentinput textsegmentinput = new connectapi.textsegmentinput(); textsegmentinput.text = 'enjoy this new file.'; messagebodyinput.messagesegments = new list<connectapi.messagesegmentinput>(); messagebodyinput.messagesegments.add(textsegmentinput); commentinput.body = messagebodyinput; connectapi.commentcapabilitiesinput commentcapabilitiesinput = new connectapi.commentcapabilitiesinput(); 374apex developer guide using salesforce features with apex connectapi.contentcapabilityinput contentcapabilityinput = new connectapi.contentcapabilityinput(); commentcapabilitiesinput.content = contentcapabilityinput; contentcapabilityinput.title = 'title'; commentinput.capabilities = commentcapabilitiesinput; string text = 'these are the contents of the new file.'; blob myblob = blob.valueof(text); connectapi.binaryinput bininput = new connectapi.binaryinput(myblob, 'text/plain', 'filename'); connectapi.comment commentrep = connectapi.chatterfeeds.postcommenttofeedelement(network.getnetworkid(), feedelementid, commentinput, bininput); post a rich-text comment with inline image make a call or use the connectapihelper repository to post a comment with an already uploaded, inline image. you can post rich-text comments with inline images and mentions two ways. use the connectapihelper repository on github to write a single line of code, or use this example, which calls postcommenttofeedelement(communityid, feedelementid, comment, feedelementfileupload). in this example, the image file is existing content that has already been uploaded to salesforce. string communityid = null; string feedelementid = '0d5r0000000sber'; string image
id = '069r00000000igq'; string mentioneduserid = '005r0000000dimz'; connectapi.commentinput input = new connectapi.commentinput(); connectapi.messagebodyinput messageinput = new connectapi.messagebodyinput(); connectapi.textsegmentinput textsegment; connectapi.mentionsegmentinput mentionsegment; connectapi.markupbeginsegmentinput markupbeginsegment; connectapi.markupendsegmentinput markupendsegment; connectapi.inlineimagesegmentinput inlineimagesegment; messageinput.messagesegments = new list<connectapi.messagesegmentinput>(); markupbeginsegment = new connectapi.markupbeginsegmentinput(); markupbeginsegment.markuptype = connectapi.markuptype.bold; messageinput.messagesegments.add(markupbeginsegment); textsegment = new connectapi.textsegmentinput(); textsegment.text = 'hello '; messageinput.messagesegments.add(textsegment); mentionsegment = new connectapi.mentionsegmentinput(); mentionsegment.id = mentioneduserid; messageinput.messagesegments.add(mentionsegment); 375apex developer guide using salesforce features with apex textsegment = new connectapi.textsegmentinput(); textsegment.text = '!'; messageinput.messagesegments.add(textsegment); markupendsegment = new connectapi.markupendsegmentinput(); markupendsegment.markuptype = connectapi.markuptype.bold; messageinput.messagesegments.add(markupendsegment); inlineimagesegment = new connectapi.inlineimagesegmentinput(); inlineimagesegment.alttext = 'image one'; inlineimagesegment.fileid = imageid; messageinput.messagesegments.add(inlineimagesegment); input.body = messageinput; connectapi.chatterfeeds.postcommenttofeedelement(communityid, feedelementid, input, null); post a rich-text feed comment with a code block call a method to post a comment with a code block. this example calls postcommenttofeedelement(communityid, feedelementid, comment, feedelementfileupload) to post a comment with a code block. string communityid = null; string feedelementid = '0d5r0000000sber'; string codesnippet = '<html>\n\t<body>\n\t\thello, world!\n\t</body>\n</html>'; connectapi.commentinput input = new connectapi.commentinput(); connectapi.messagebodyinput messageinput = new connectapi.messagebodyinput(); connectapi.textsegmentinput textsegment; connectapi.markupbeginsegmentinput markupbeginsegment; connectapi.markupendsegmentinput markupendsegment; messageinput.messagesegments = new list<connectapi.messagesegmentinput>(); markupbeginsegment = new connectapi.markupbeginsegmentinput(); markupbeginsegment.markuptype = connectapi.markuptype.code; messageinput.messagesegments.add(markupbeginsegment); textsegment = new connectapi.textsegmentinput(); textsegment.text = codesnippet; messageinput.messagesegments.add(textsegment); markupendsegment = new connectapi.markupendsegmentinput(); markupendsegment.markuptype = connectapi.markuptype.code; messageinput.messagesegments.add(markupendsegment); input.body = messageinput; connectapi.chatterfeeds.postcommenttofeedelement(communityid, feedelementid, input, null); 376apex developer guide using salesforce features with apex edit a comment call a method to edit a comment. call updatecomment(communityid, commentid, comment) to edit a comment. string commentid; string communityid = network.getnetworkid(); // get the last feed item created by the context user. list<feeditem> feeditems = [select id from feeditem where createdbyid = :userinfo.getuserid() order by createddate desc]; if (
feeditems.isempty()) { // return null within anonymous apex. return null; } string feedelementid = feeditems[0].id; connectapi.commentpage commentpage = connectapi.chatterfeeds.getcommentsforfeedelement(communityid, feedelementid); if (commentpage.items.isempty()) { // return null within anonymous apex. return null; } commentid = commentpage.items[0].id; connectapi.feedentityiseditable iseditable = connectapi.chatterfeeds.iscommenteditablebyme(communityid, commentid); if (iseditable.iseditablebyme == true){ connectapi.commentinput commentinput = new connectapi.commentinput(); connectapi.messagebodyinput messagebodyinput = new connectapi.messagebodyinput(); connectapi.textsegmentinput textsegmentinput = new connectapi.textsegmentinput(); messagebodyinput.messagesegments = new list<connectapi.messagesegmentinput>(); textsegmentinput.text = 'this is my edited comment.'; messagebodyinput.messagesegments.add(textsegmentinput); commentinput.body = messagebodyinput; connectapi.comment editedcomment = connectapi.chatterfeeds.updatecomment(communityid, commentid, commentinput); } follow a record call a method to follow a record. 377apex developer guide using salesforce features with apex call follow(communityid, userid, subjectid) to follow a record. chatterusers.connectapi.subscription subscriptiontorecord = connectapi.chatterusers.follow(null, 'me', '001rr000002g4y0'); see also: unfollow a record unfollow a record call a method to stop following a record. when you follow a record such as a user, the call to connectapi.chatterusers.follow returns a connectapi.subscription object. to unfollow a record, pass the id property of that object to deletesubscription(communityid, subscriptionid). connectapi.chatter.deletesubscription(null, '0e8rr0000004cnk0au'); see also: follow a record get a repository call a method to get a repository. call getrepository(repositoryid) to get a repository. final string repositoryid = '0xcxx0000000123gaa'; final connectapi.contenthubrepository repository = connectapi.contenthub.getrepository(repositoryid); get repositories call a method to get all repositories. call getrepositories() to get all repositories and get the first sharepoint online repository found. final string sharepointonlineprovidertype ='contenthubsharepointoffice365'; final connectapi.contenthubrepositorycollection repositorycollection = connectapi.contenthub.getrepositories(); connectapi.contenthubrepository sharepointonlinerepository = null; for(connectapi.contenthubrepository repository : repositorycollection.repositories){ if(sharepointonlineprovidertype.equalsignorecase(repository.providertype.type)){ sharepointonlinerepository = repository; break; } } get allowed item types call a method to get allowed item types. 378apex developer guide using salesforce features with apex call getalloweditemtypes(repositoryid, repositoryfolderid, filter) with a filter of filesonly to get the first connectapi.contenthubitemtypesummary.id of a file. the context user can create allowed files in a repository folder in the external system. final connectapi.contenthuballoweditemtypecollection alloweditemtypescoll = connectapi.contenthub.getalloweditemtypes(repositoryid, repositoryfolderid, connectapi.contenthubitemtype.filesonly); final list<connectapi.contenthubitemtypesummary> alloweditemtypes = alloweditemtypescoll.alloweditemtypes; string allowedfileitemtypeid = null; if(alloweditemtypes.size() > 0){ connectapi.contenthubitemtypesummary alloweditemtypesummary = alloweditemtypes.get(0); allowedfileitemtypeid = alloweditemtypesummary.id; } get previews call a method to get all supported preview formats and their respective urls. call getpreviews(repositoryid, repositoryfileid) to get all
supported preview formats and their respective urls and number of renditions. for each supported preview format, we show every rendition url available. final string gdriverepositoryid = '0xcxx00000000odgay', gdrivefileid = 'document:1-zca1baeoqbo2_ynfihcck6qjtpmoke-khfc4tyg3rk'; final connectapi.filepreviewcollection previewscollection = connectapi.contenthub.getpreviews(gdriverepositoryid, gdrivefileid); for(connectapi.filepreview filepreview : previewscollection.previews){ system.debug(string.format('preview - url: \'\'{0}\'\', format: \'\'{1}\'\', nbr of renditions for this format: {2}', new string[]{ filepreview.url, filepreview.format.name(),string.valueof(filepreview.previewurls.size())})); for(connectapi.filepreviewurl filepreviewurl : filepreview.previewurls){ system.debug('-----> rendition url: ' + filepreviewurl.previewurl); } } get a file preview call a method to get a file preview. call getfilepreview(repositoryid, repositoryfileid, formattype) with a formattype of thumbnail to get the thumbnail format preview along with its respective url and number of thumbnail renditions. for each thumbnail format, we show every rendition url available. final string gdriverepositoryid = '0xcxx00000000odgay', gdrivefileid = 'document:1-zca1baeoqbo2_ynfihcck6qjtpmoke-khfc4tyg3rk'; final connectapi.filepreviewcollection previewscollection = connectapi.contenthub.getpreviews(gdriverepositoryid, gdrivefileid); for(connectapi.filepreview filepreview : previewscollection.previews){ system.debug(string.format('preview - url: \'\'{0}\'\', format: \'\'{1}\'\', nbr of renditions for this format: {2}', new string[]{ filepreview.url, filepreview.format.name(),string.valueof(filepreview.previewurls.size())})); for(connectapi.filepreviewurl filepreviewurl : filepreview.previewurls){ system.debug('-----> rendition url: ' + filepreviewurl.previewurl); 379apex developer guide using salesforce features with apex } } get repository folder items call a method to get a collection of repository folder items. call getrepositoryfolderitems(repositoryid, repositoryfolderid) to get the collection of items in a repository folder. for files, we show the file’s name, size, external url, and download url. for folders, we show the folder’s name, description, and external url. final string gdriverepositoryid = '0xcxx00000000odgay', gdrivefolderid = 'folder:0b0ltys1kmm3ssvj2bjiztgfqsws'; final connectapi.repositoryfolderitemscollection folderitemscoll = connectapi.contenthub.getrepositoryfolderitems(gdriverepositoryid,gdrivefolderid); final list<connectapi.repositoryfolderitem> folderitems = folderitemscoll.items; system.debug('number of items in repository folder: ' + folderitems.size()); for(connectapi.repositoryfolderitem item : folderitems){ connectapi.repositoryfilesummary filesummary = item.file; if(filesummary != null){ system.debug(string.format('file item - name: \'\'{0}\'\', size: {1}, external url: \'\'{2}\'\', download url: \'\'{3}\'\'', new string[]{ filesummary.name, string.valueof(filesummary.contentsize), filesummary.externaldocumenturl, filesummary.downloadurl})); }else{ connectapi.repositoryfoldersummary foldersummary = item.folder; system.debug(string.format('folder item - name: \'\'{0}\'\', description: \'\'{1}\'\'', new string[]{ foldersummary.name, foldersummary.description})); } } get a
repository folder call a method to get a repository folder. call getrepositoryfolder(repositoryid, repositoryfolderid) to get a repository folder. final string gdriverepositoryid = '0xcxx00000000odgay', gdrivefolderid = 'folder:0b0ltys1kmm3ssvj2bjiztgfqsws'; final connectapi.repositoryfolderdetail folder = connectapi.contenthub.getrepositoryfolder(gdriverepositoryid, gdrivefolderid); system.debug(string.format('folder - name: \'\'{0}\'\', description: \'\'{1}\'\', external url: \'\'{2}\'\', folder items url: \'\'{3}\'\'', new string[]{ folder.name, folder.description, folder.externalfolderurl, folder.folderitemsurl})); get a repository file without permissions information call a method to get a repository file without permission information. call getrepositoryfile(repositoryid, repositoryfileid) to get a repository file without permissions information. final string gdriverepositoryid = '0xcxx00000000odgay', gdrivefileid = 'file:0b0ltys1kmm3stmxknjvjbwzja00'; final connectapi.repositoryfiledetail file = 380apex developer guide using salesforce features with apex connectapi.contenthub.getrepositoryfile(gdriverepositoryid, gdrivefileid); system.debug(string.format('file - name: \'\'{0}\'\', size: {1}, external url: \'\'{2}\'\', download url: \'\'{3}\'\'', new string[]{ file.name, string.valueof(file.contentsize), file.externaldocumenturl, file.downloadurl})); get a repository file with permissions information call a method to get a repository file with permission information. call getrepositoryfile(repositoryid, repositoryfileid, includeexternalfilepermissionsinfo) to get a repository file with permissions information. final string gdriverepositoryid = '0xcxx00000000odgay', gdrivefileid = 'file:0b0ltys1kmm3stmxknjvjbwzja00'; final connectapi.repositoryfiledetail file = connectapi.contenthub.getrepositoryfile(gdriverepositoryid, gdrivefileid, true); system.debug(string.format('file - name: \'\'{0}\'\', size: {1}, external url: \'\'{2}\'\', download url: \'\'{3}\'\'', new string[]{ file.name, string.valueof(file.contentsize), file.externaldocumenturl, file.downloadurl})); final connectapi.externalfilepermissioninformation externalfileperminfo = file.externalfilepermissioninformation; //permission types final list<connectapi.contenthubpermissiontype> permissiontypes = externalfileperminfo.externalfilepermissiontypes; for(connectapi.contenthubpermissiontype permissiontype : permissiontypes){ system.debug(string.format('permission type - id: \'\'{0}\'\', label: \'\'{1}\'\'', new string[]{ permissiontype.id, permissiontype.label})); } //permission groups final list<connectapi.repositorygroupsummary> groups = externalfileperminfo.repositorypublicgroups; for(connectapi.repositorygroupsummary ggroup : groups){ system.debug(string.format('group - id: \'\'{0}\'\', name: \'\'{1}\'\', type: \'\'{2}\'\'', new string[]{ ggroup.id, ggroup.name, ggroup.type.name()})); } create a repository file without content (metadata only) call a method to create a file without binary content (metadata only) in a google drive repository folder. call addrepositoryitem(repositoryid, repositoryfolderid, file) to create a file without binary content (metadata only) in a google drive repository folder. after the file is created, we show the file’s id, name, description, external url, and download url. final string gdriverepositoryid = '0xcxx
00000000odgay', gdrivefolderid = 'folder:0b0ltys1kmm3ssvj2bjiztgfqsws'; final connectapi.contenthubiteminput newitem = new connectapi.contenthubiteminput(); newitem.itemtypeid = 'document'; //see getallowedtypes for any file item types available for creation/update 381apex developer guide using salesforce features with apex newitem.fields = new list<connectapi.contenthubfieldvalueinput>(); //metadata: name field final connectapi.contenthubfieldvalueinput fieldvalueinput = new connectapi.contenthubfieldvalueinput(); fieldvalueinput.name = 'name'; fieldvalueinput.value = 'new folder item name.txt'; newitem.fields.add(fieldvalueinput); //metadata: description field final connectapi.contenthubfieldvalueinput fieldvalueinputdesc = new connectapi.contenthubfieldvalueinput(); fieldvalueinputdesc.name = 'description'; fieldvalueinputdesc.value = 'it does describe it'; newitem.fields.add(fieldvalueinputdesc); final connectapi.repositoryfolderitem newfolderitem = connectapi.contenthub.addrepositoryitem(gdriverepositoryid, gdrivefolderid, newitem); final connectapi.repositoryfilesummary newfile = newfolderitem.file; system.debug(string.format('new file - id: \'\'{0}\'\', name: \'\'{1}\'\', description: \'\'{2}\'\' \n external url: \'\'{3}\'\', download url: \'\'{4}\'\'', new string[]{ newfile.id, newfile.name, newfile.description, newfile.externaldocumenturl, newfile.downloadurl})); see also: apex reference guide: connectapi.contenthubiteminput apex reference guide: connectapi.contenthubfieldvalueinput create a repository file with content call a method to create a file with binary content in a google drive repository folder. call addrepositoryitem(repositoryid, repositoryfolderid, file, filedata) to create a file with binary content in a google drive repository folder. after the file is created, we show the file’s id, name, description, external url, and download url. final string gdriverepositoryid = '0xcxx00000000odgay', gdrivefolderid = 'folder:0b0ltys1kmm3ssvj2bjiztgfqsws'; final connectapi.contenthubiteminput newitem = new connectapi.contenthubiteminput(); newitem.itemtypeid = 'document'; //see getallowedtypes for any file item types available for creation/update newitem.fields = new list<connectapi.contenthubfieldvalueinput>(); //metadata: name field final string newfilename = 'new folder item name.txt'; final connectapi.contenthubfieldvalueinput fieldvalueinput = new connectapi.contenthubfieldvalueinput(); fieldvalueinput.name = 'name'; fieldvalueinput.value = newfilename; newitem.fields.add(fieldvalueinput); //metadata: description field 382apex developer guide using salesforce features with apex final connectapi.contenthubfieldvalueinput fieldvalueinputdesc = new connectapi.contenthubfieldvalueinput(); fieldvalueinputdesc.name = 'description'; fieldvalueinputdesc.value = 'it does describe it'; newitem.fields.add(fieldvalueinputdesc); //binary content final blob newfileblob = blob.valueof('awesome content for brand new file'); final string newfilemimetype = 'text/plain'; final connectapi.binaryinput filebinaryinput = new connectapi.binaryinput(newfileblob, newfilemimetype, newfilename); final connectapi.repositoryfolderitem newfolderitem = connectapi.contenthub.addrepositoryitem(gdriverepositoryid, gdrivefolderid, newitem, filebinaryinput); final connectapi.repositoryfilesummary newfile = newfolderitem.file; system.debug(string.format('new file - id: \'\'{0}\'\', name: \'\'{1}\'\', description: \'\'
{2}\'\' \n external url: \'\'{3}\'\', download url: \'\'{4}\'\'', new string[]{ newfile.id, newfile.name, newfile.description, newfile.externaldocumenturl, newfile.downloadurl})); see also: apex reference guide: connectapi.contenthubiteminput apex reference guide: connectapi.contenthubfieldvalueinput apex reference guide: connectapi.binaryinput update a repository file without content (metadata only) call a method to update the metadata of a repository file. call updaterepositoryfile(repositoryid, repositoryfileid, file) to update the metadata of a file in a repository folder. after the file is updated, we show the file’s id, name, description, external url, download url. final string gdriverepositoryid = '0xcxx00000000odgay', gdrivefolderid = 'folder:0b0ltys1kmm3ssvj2bjiztgfqsws', gdrivefileid = 'document:1q9oatvpcyybk-jwzp_phr75ulqghwfp15zhkamkrrcq'; final connectapi.contenthubiteminput updateditem = new connectapi.contenthubiteminput(); updateditem.itemtypeid = 'document'; //see getallowedtypes for any file item types available for creation/update updateditem.fields = new list<connectapi.contenthubfieldvalueinput>(); //metadata: name field final connectapi.contenthubfieldvalueinput fieldvalueinputname = new connectapi.contenthubfieldvalueinput(); fieldvalueinputname.name = 'name'; fieldvalueinputname.value = 'updated file name.txt'; updateditem.fields.add(fieldvalueinputname); final connectapi.repositoryfiledetail updatedfile = connectapi.contenthub.updaterepositoryfile(gdriverepositoryid, gdrivefileid, updateditem); system.debug(string.format('updated file - id: \'\'{0}\'\', name: \'\'{1}\'\', description: \'\'{2}\'\',\n external url: \'\'{3}\'\', download url: \'\'{4}\'\'', new string[]{ 383apex developer guide using salesforce features with apex updatedfile.id, updatedfile.name, updatedfile.description, updatedfile.externaldocumenturl, updatedfile.downloadurl})); see also: apex reference guide: connectapi.contenthubiteminput apex reference guide: connectapi.contenthubfieldvalueinput update a repository file with content call a method to update a repository file with content. call updaterepositoryfile(repositoryid, repositoryfileid, file, filedata) to update the content and metadata of a file in a repository. after the file is updated, we show the file’s id, name, description, external url, and download url. final string gdriverepositoryid = '0xcxx00000000odgay', gdrivefolderid = 'folder:0b0ltys1kmm3ssvj2bjiztgfqsws', gdrivefileid = 'document:1q9oatvpcyybk-jwzp_phr75ulqghwfp15zhkamkrrcq'; final connectapi.contenthubiteminput updateditem = new connectapi.contenthubiteminput(); updateditem.itemtypeid = 'document'; //see getallowedtypes for any file item types available for creation/update updateditem.fields = new list<connectapi.contenthubfieldvalueinput>(); //metadata: name field final connectapi.contenthubfieldvalueinput fieldvalueinputname = new connectapi.contenthubfieldvalueinput(); fieldvalueinputname.name = 'name'; fieldvalueinputname.value = 'updated file name.txt'; updateditem.fields.add(fieldvalueinputname); //binary content final blob updatedfileblob = blob.valueof('even more awesome content for updated file'); final string updatedfilemimetype = 'text/plain'; final connectapi.binaryinput filebinaryinput = new connectapi.binaryinput(updatedfileblob, updatedfilemimetype,
updatedfilename); final connectapi.repositoryfiledetail updatedfile = connectapi.contenthub.updaterepositoryfile(gdriverepositoryid, gdrivefileid, updateditem); system.debug(string.format('updated file - id: \'\'{0}\'\', name: \'\'{1}\'\', description: \'\'{2}\'\',\n external url: \'\'{3}\'\', download url: \'\'{4}\'\'', new string[]{ updatedfile.id, updatedfile.name, updatedfile.description, updatedfile.externaldocumenturl, updatedfile.downloadurl})); see also: apex reference guide: connectapi.contenthubiteminput apex reference guide: connectapi.contenthubfieldvalueinput apex reference guide: connectapi.binaryinput get an authentication url call a method to get an authentication url. 384apex developer guide using salesforce features with apex call getoauthcredentialauthurl(requestbody) to retrieve the url that a user must visit to begin an authentication flow, ultimately returning authentication tokens to salesforce. accepts input parameters representing a specific external credential and, optionally, a named principal. use this method as part of building a customized or branded user interface to help users initiate authentication. connectapi.oauthcredentialauthurlinput input = new connectapi.oauthcredentialauthurlinput(); input.externalcredential = 'myexternalcredentialdevelopername'; input.principaltype = connectapi.credentialprincipaltype.peruserprincipal; input.principalname = 'myprincipal'; // only required when principaltype = namedprincipal connectapi.oauthcredentialauthurl output = connectapi.namedcredentials.getoauthcredentialauthurl(input); string authenticationurl = output.authenticationurl; // redirect users to this url to authenticate in the browser see also: apex reference guide: namedcredentials methods connect in apex features this topic describes which classes and methods to use to work with common connect in apex features. you can also go directly to the connectapi namespace reference content. in this section: working with action links an action link is a button on a feed element. clicking an action link can take a user to a web page, initiate a file download, or invoke an api call to salesforce or to an external server. an action link includes a url and an http method, and can include a request body and header information, such as an oauth token for authentication. use action links to integrate salesforce and third-party services into the feed so that users can drive productivity and accelerate innovation. working with feeds and feed elements the chatter feed is a container of feed elements. the abstract class connectapi.feedelement is a parent class to the connectapi.feeditem class, representing feed posts, and the connectapi.genericfeedelement class, representing bundles and recommendations in the feed. accessing connectapi data in experience cloud sites many connectapi methods work within the context of a single experience cloud site. methods available to experience cloud guest users if your experience cloud site allows access without logging in, guest users have access to many apex methods. these methods return information the guest user has access to. supported validations for dbt segments when creating or updating a segment, the connectapi.cdpsegmentinput class is subject to some sql validations. 385apex developer guide using salesforce features with apex working with action links an action link is a button on a feed element. clicking an action link can take a user to a web page, initiate a file download, or invoke an api call to salesforce or to an external server. an action link includes a url and an http method, and can include a request body and header information, such as an oauth token for authentication. use action links to integrate salesforce and third-party services into the feed so that users can drive productivity and accelerate innovation. workflow this feed item contains one action link group with one visible action link, join. the workflow to create and post action links with a feed element: 1. (optional) create an action link template. 2. call connectapi.actionlinks.createactionlinkgroupdefinition(communityid, actionlinkgroup) to define an action link group that contains at least one action link. 3. call connectapi.chatterfeeds.postfeedelement(communityid, feedelement) to
post a feed element and associate the action link with it. use these methods to work with action links: connectapi method task actionlinks.createactionlinkgroupdefinition create an action link group definition. to associate an action link (communityid, actionlinkgroup) group with a feed element, first create an action link group definition. then post a feed element with an associated actions actionlinks.deleteactionlinkgroupdefinition(communityid, capability. actionlinkgroupid) actionlinks.getactionlinkgroupdefinition(communityid, actionlinkgroupid) chatterfeeds.postfeedelement(communityid, post a feed element with an associated actions capability. associate feedelement) up to 10 action link groups with a feed element. 386apex developer guide using salesforce features with apex connectapi method task actionlinks.getactionlink(communityid, get information about an action link, including state for the context actionlinkid) user. actionlinks.getactionlinkgroup(communityid, get information about an action link group including state for the actionlinkgroupid) context user. actionlinks.getactionlinkdiagnosticinfo(communityid, get diagnostic information returned when an action link executes. actionlinkid) diagnostic information is given only for users who can access the action link. chatterfeeds.getfeedelementsfromfeed() get the feed elements from a specified feed type. if a feed element has action links associated with it, the action links data is returned in the feed element’s associated actions capability. in this section: action links overview, authentication, and security learn about apex action links security, authentication, labels, and errors. action links use case use action links to integrate salesforce and third-party services with a feed. an action link can make an http request to a salesforce or third-party api. an action link can also download a file or open a web page. this topic contains an example use case. see also: define an action link and post with a feed element define an action link in a template and post with a feed element action links overview, authentication, and security learn about apex action links security, authentication, labels, and errors. workflow this feed item contains one action link group with one visible action link, join. 387apex developer guide using salesforce features with apex the workflow to create and post action links with a feed element: 1. (optional) create an action link template. 2. call connectapi.actionlinks.createactionlinkgroupdefinition(communityid, actionlinkgroup) to define an action link group that contains at least one action link. 3. call connectapi.chatterfeeds.postfeedelement(communityid, feedelement) to post a feed element and associate the action link with it. action link templates create action link templates in setup to instantiate action link groups with common properties. you can package templates and distribute them to other salesforce orgs. specify binding variables in the template and set the values of the variables when you instantiate the action link group. for example, use a binding variable for the api version number, a user id, or an oauth token. you can also specify context variables in the templates. when a user executes the action link, salesforce provides values for these variables, such as who executed the link and in which organization. to instantiate the action link group, call the connectapi.actionlinks.createactionlinkgroupdefinition(communityid, actionlinkgroup) method. specify the template id and the values for any binding variables defined in the template. see design action link templates. type of action links specify the action link type in the actiontype property when you define an action link. there are four types of action links: • api—the action link calls a synchronous api at the action url. salesforce sets the status to successfulstatus or failedstatus based on the http status code returned by your server. 388apex developer guide using salesforce features with apex • apiasync—the action link calls an asynchronous api at the action url. the action remains in a pendingstatus state until a third party makes a request to /connect/action-links/actionlinkid to set the status to successfulstatus or failedstatus when the asynchronous operation is complete. • download—the action link downloads a file from the action url. • ui—the action link takes the user to a web page at the action url. authentication when you define an action link, specify a url (actionurl) and the http headers (headers) required to make
a request to that url. if an external resource requires authentication, include the information wherever the resource requires. if a salesforce resource requires authentication, you can include oauth information in the http headers or you can include a bearer token in the url. salesforce automatically authenticates these resources. • relative urls in templates • relative urls beginning with /services/apexrest when the action link group is instantiated from apex don’t use these resources for sensitive operations. security https the action url in an action link must begin with https:// or be a relative url that matches one of the rules in the previous authentication section. encryption api details are stored with encryption, and obfuscated for clients. the actionurl, headers, and requestbody data for action links that are not instantiated from a template are encrypted with the organization’s encryption key. the action url, http headers, and http request body for an action link template are not encrypted. the binding values used when instantiating an action link group from a template are encrypted with the organization’s encryption key. action link templates only users with customize application user permission can create, edit, delete, and package action link templates in setup. don’t store sensitive information in templates. use binding variables to add sensitive information when you instantiate the action link group. after the action link group is instantiated, the values are stored in an encrypted format. see define binding variables in design action link templates. connected apps when creating action links via a connected app, it's a good idea to use a connected app with a consumer key that never leaves your control. the connected app is used for server-to-server communication and is not compiled into mobile apps that could be decompiled. expiration date when you define an action link group, specify an expiration date (expirationdate). after that date, the action links in the group can’t be executed and disappear from the feed. if your action link group definition includes an oauth token, set the group’s expiration date to the same value as the expiration date of the oauth token. action link templates use a slightly different mechanism for excluding a user. see set the action link group expiration time in design action link templates. 389apex developer guide using salesforce features with apex exclude a user or specify a user use the excludeuserid property of the action link definition input to exclude a single user from executing an action. use the userid property of the action link definition input to specify the id of a user who alone can execute the action. if you don’t specify a userid property or if you pass null, any user can execute the action. you can’t specify both excludeuserid and userid for an action link action link templates use a slightly different mechanism for excluding a user. see set who can see the action link in design action link templates. read, modify, or delete an action link group definition there are two views of an action link and an action link group: the definition, and the context user’s view. the definition includes potentially sensitive information, such as authentication information. the context user’s view is filtered by visibility options and the values reflect the state of the context user. action link group definitions can contain sensitive information (such as oauth tokens). for this reason, to read, modify, or delete a definition, the user must have created the definition or have view all data permission. in addition, in connect rest api, the request must be made via the same connected app that created the definition. in apex, the call must be made from the same namespace that created the definition. context variables use context variables to pass information about the user who executed the action link and the context in which it was invoked into the http request made by invoking an action link. you can use context variables in the actionurl, headers, and requestbody properties of the action link definition input request body or connectapi.actionlinkdefinitioninput object. you can also use context variables in the action url, http request body, and http headers fields of action link templates. you can edit these fields, including adding and removing context variables, after a template is published. the context variables are: context variable description {!actionlinkid} the id of the action link the user executed. {!actionlinkgroupid} the id of the action link group containing the action link the user executed. {!communityid} the id of the site in which the user executed the action link. the value for your internal org is the empty key "000000000000000000". {!communityurl} the
url of the site in which the user executed the action link. the value for your internal org is empty string "". {!orgid} the id of the org in which the user executed the action link. {!userid} the id of the user that executed the action link. versioning to avoid issues due to upgrades or changing functionality in your api, we recommend using versioning when defining action links. for example, the actionurl property in the connectapi.actionlinkdefinitioninputlooks like https://www.example.com/api/v1/exampleresource. 390apex developer guide using salesforce features with apex you can use templates to change the values of the actionurl, headers, or requestbody properties, even after a template is distributed in a package. let’s say you release a new api version that requires new inputs. an admin can change the inputs in the action link template in setup and even action links already associated with a feed element use the new inputs. however, you can’t add new binding variables to a published action link template. if your api isn’t versioned, you can use the expirationdate property of the connectapi.actionlinkgroupdefinitioninput to avoid issues due to upgrades or changing functionality in your api. see set the action link group expiration time in design action link templates. errors use the action link diagnostic information method (connectapi.actionlinks.getactionlinkdiagnosticinfo(communityid, actionlinkid)) to return status codes and errors from executing api action links. diagnostic info is given only for users who can access the action link. localized labels action links use a predefined set of localized labels specified in the labelkey property of the connectapi.actionlinkdefinitioninput request body and the label field of an action link template. for a list of labels, see actions links labels. note: if none of the label key values make sense for your action link, specify a custom label in the label field of an action link template and set label key to none. however, custom labels aren’t localized. see also: define an action link and post with a feed element define an action link in a template and post with a feed element define an action link and post with a feed element define an action link in a template and post with a feed element action links use case use action links to integrate salesforce and third-party services with a feed. an action link can make an http request to a salesforce or third-party api. an action link can also download a file or open a web page. this topic contains an example use case. start a video chat from the feed suppose that you work as a salesforce developer for a company that has a salesforce org and an account with a fictional company called “videochat.” users have been saying they want to do more from their mobile devices. you’re asked to create an app that lets users create and join video chats directly from their mobile device. when a user opens the videochat app in salesforce, they’re asked to name the video chat room and invite either a group or individual users to the video chat room. when the user clicks ok, the videochat app launches the video chat room and posts a feed item to the selected group or users asking them to please join the video chat by clicking an action link labeled join. when an invitee clicks join, the action link opens a web page containing the video chat room. 391apex developer guide using salesforce features with apex as a developer thinking about how to create the action link url, you come up with these requirements: 1. when a user clicks join, the action link url has to open the video chat room they were invited to. 2. the action link url has to tell the video chat room who’s joining. to dynamically create the action link urls, you create an action link template in setup. for the first requirement, you create a {!bindings.roomid} binding variable in the action url template field. when the user clicks ok to create the video chat room, your apex code generates a unique room id. the apex code uses that unique room id as the binding variable value when it instantiates the action link group, associates it with the feed item, and posts the feed item. for the second requirement, the action link must include the user id. action links support a predefined set of context variables. when an action link is invoked, salesforce substitutes the variables with values. context variables include information about who clicked the action link and in what context it was invoked. you decide to include a {!userid
} context variable in the action url so that when a user clicks the action link in the feed, salesforce substitutes the user’s id and the video chat room knows who’s entering. this is the action link template for the join action link. 392apex developer guide using salesforce features with apex every action link must be associated with an action link group. the group defines properties shared by all the action links associated with it. even if you’re using a single action link (as in this example) it must be associated with a group. the first field of the action link template is action link group template, which in this case is video chat, which is the action link group template the action link template is associated with. . working with feeds and feed elements the chatter feed is a container of feed elements. the abstract class connectapi.feedelement is a parent class to the connectapi.feeditem class, representing feed posts, and the connectapi.genericfeedelement class, representing bundles and recommendations in the feed. note: salesforce help refers to feed items as posts and bundles as bundled posts. 393apex developer guide using salesforce features with apex capabilities as part of the effort to diversify the feed, pieces of functionality found in feed elements have been broken out into capabilities. capabilities provide a consistent way to interact with the feed. don’t inspect the feed element type to determine which functionality is available for a feed element. inspect the capability, which tells you explicitly what’s available. check for the presence of a capability to determine what a client can do to a feed element. the connectapi.feedelement.capabilities property holds a set of capabilities. a capability includes both an indication that a feature is possible and data associated with that feature. if a capability property exists on a feed element, that capability is available, even if there isn’t any data associated with the capability yet. for example, if the chatterlikes capability property exists on a feed element, the context user can like that feed element. if the capability property doesn’t exist on a feed element, it isn’t possible to like that feed element. when posting a feed element, specify its characteristics in the connectapi.feedelementinput.capabilities property. how the salesforce ui displays feed items a client can use the connectapi.feedelement.capabilities property to determine what it can do with a feed element and how to render the feed element. for all feed element subclasses other than connectapi.feeditem, the client doesn’t have to know the subclass type. instead, the client can look at the capabilities. feed items do have capabilities, but they also have a few properties, such as actor, that aren’t exposed as capabilities. for this reason, clients must handle feed items a bit differently than other feed elements. the salesforce ui uses one layout to display every feed item. this single layout gives customers a consistent view of feed items and gives developers an easy way to create ui. the layout always contains the same pieces and the pieces are always in the same position. only the content of the layout pieces changes. the feed item (connectapi.feeditem) layout elements are: 1. actor (connectapi.feeditem.actor)—a photo or icon of the creator of the feed item. (you can override the creator at the feed item type level. for example, the dashboard snapshot feed item type shows the dashboard as the creator.) 2. header (connectapi.feedelement.header)—context for the feed item. the same feed item can have a different header depending on who posted it and where it was posted. for example, ted posted this feed item to a group. timestamp (connectapi.feedelement.relativecreateddate)—the date and time when the feed item was posted. if the feed item is less than two days old, the date and time are formatted as a relative, localized string, such as “17m ago”. otherwise, the date and time are formatted as an absolute, localized string. 394apex developer guide using salesforce features with apex 3. body (connectapi.feedelement.body)—all feed items have a body. the body can be null, which is the case when the user doesn’t provide text for the feed item. because the body can be null, you can’t use it as the default case for rendering text. instead, use the connectapi.feedelement.header.text property, which always contains a value. 4. auxiliary body (connectapi.feedelement.capabilities)—the visualization
of the capabilities. see capabilities. how the salesforce displays feed elements other than feed items a client can use the connectapi.feedelement.capabilities property to determine what it can do with a feed element and how to render the feed element. this section uses bundles as an example of how to render a feed element, but these properties are available for every feed element. capabilities allow you to handle all content in the feed consistently. note: bundled posts contain feed-tracked changes and are in record feeds only. to give customers a clean, organized feed, salesforce aggregates feed-tracked changes into a bundle. to see individual feed elements, click the bundle. a bundle is a connectapi.genericfeedelement object (which is a concrete subclass of connectapi.feedelement) with a conenctapi.bundlecapability. the bundle layout elements are: • header (connectapi.feedelement.header)—for feed-tracked change bundles, this text is “user name updated this record.” • timestamp (connectapi.feedelement.relativecreateddate)—the date and time when the feed item was posted. if the feed item is less than two days old, the date and time are formatted as a relative, localized string, such as “17m ago”. otherwise, the date and time are formatted as an absolute, localized string. • auxiliary body (connectapi.feedelement.capabilities.bundle.changes)—the bundle displays the fieldname and the oldvalue and newvalue properties for the first two feed-tracked changes in the bundle. if there are more than two feed-tracked changes, the bundle displays a “show all updates” link. feed element visibility the feed elements a user sees depend on how the administrator has configured feed tracking, sharing rules, and field-level security. for example, if a user doesn’t have access to a record, they don’t see updates for that record. if a user can see the parent of the feed element, the user can see the feed element. typically, a user sees feed updates for: • feed elements that @mention the user (if the user can access the feed element’s parent) • feed elements that @mention groups the user is a member of • record field changes on records whose parent is a record the user can see, including user, group, and file records • feed elements posted to the user • feed elements posted to groups that the user owns or is a member of • feed elements for standard and custom records, for example, tasks, events, leads, accounts, files 395apex developer guide using salesforce features with apex feed types there are many types of feeds. each feed type defines a collection of feed elements. important: the collection of feed elements can change between releases. all feed types except favorites are exposed in the connectapi.feedtype enum and passed to one of the connectapi.chatterfeeds.getfeedelementsfromfeed methods. this example gets the feed elements from the context user’s news feed and topics feed. connectapi.feedelementpage newsfeedelementpage = connectapi.chatterfeeds.getfeedelementsfromfeed(null, connectapi.feedtype.news, 'me'); connectapi.feedelementpage topicsfeedelementpage = connectapi.chatterfeeds.getfeedelementsfromfeed(null, connectapi.feedtype.topics, '0tod00000000cld'); to get a filter feed, call one of the connectapi.chatterfeeds.getfeedelementsfromfilterfeed methods. to get a favorites feed, call one of the connectapi.chatterfavorites.getfeedelements methods. the feed types and their descriptions are: • bookmarks—contains all feed items saved as bookmarks by the context user. • company—contains all feed items except feed items of type trackedchange. to see the feed item, the user must have sharing access to its parent. • directmessagemoderation—contains all direct messages that are flagged for moderation. the direct message moderation feed is available only to users with moderate experiences chatter messages permissions. • directmessages—contains all feed items of the context user’s direct messages. • draft—contains all the feed items that the context user drafted. • files—contains all feed items that contain files posted by people or groups that the context user follows. • filter—contains the news feed filtered to contain feed items whose parent is a
specified object type. • groups—contains all feed items from all groups the context user either owns or is a member of. • home—contains all feed items associated with any managed topic in an experience cloud site. • landing—contains all feed items that best drive user engagement when the feed is requested. allows clients to avoid an empty feed when there aren’t many personalized feed items. • moderation—contains all feed items that are flagged for moderation, except direct messages. the moderation feed is available only to users with moderate experiences feeds permissions. • mute—contains all feed items that the context user muted. • news—contains all updates for people the context user follows, groups the user is a member of, and files and records the user is following. contains all updates for records whose parent is the context user. • pendingreview—contains all feed items and comments that are pending review. • people—contains all feed items posted by all people the context user follows. • record—contains all feed items whose parent is a specified record, which could be a group, user, object, file, or any other standard or custom object. when the record is a group, the feed also contains feed items that mention the group. when the record is a user, the feed contains only feed items on that user. you can get another user’s record feed. • streams—contains all feed items for any combination of up to 25 feed-enabled entities that the context user subscribes to in a stream. examples of feed-enabled entities include people, groups, and records, 396
apex developer guide using salesforce features with apex • to—contains all feed items with mentions of the context user. contains feed items the context user commented on and feed items created by the context user that are commented on. • topics—contains all feed items that include the specified topic. • userprofile—contains feed items created when a user changes records that can be tracked in a feed. contains feed items whose parent is the user and feed items that @mention the user. this feed is different than the news feed, which returns more feed items, including group updates. you can get another user’s user profile feed. • favorites—contains favorites saved by the context user. favorites are feed searches, list views, and topics. post a feed item using postfeedelement tip: the postfeedelement methods are the simplest, most efficient way to post feed items because, unlike the postfeeditem methods, they don’t require you to pass a feed type. feed items are the only feed element type you can post. use these methods to post feed items. postfeedelement(communityid, subjectid, feedelementtype, text) post a plain-text feed element. postfeedelement(communityid, feedelement, feedelementfileupload) (version 35.0 and earlier) post a rich-text feed element. include mentions and hashtag topics, attach a file to a feed element, and associate action link groups with a feed element. you can also use this method to share a feed element and add a comment. postfeedelement(communityid, feedelement) (version 36.0 and later) post a rich-text feed element. include mentions and hashtag topics, attach already uploaded files to a feed element, and associate action link groups with a feed element. you can also use this method to share a feed element and add a comment. when you post a feed item, you create a child of a standard or custom object. specify the parent object in the subjectid parameter or in the subjectid property of the connectapi.feedelementinput object you pass in the feedelement parameter. the value of the subjectid parameter determines the feeds in which the feed item is displayed. the parent property in the returned connectapi.feeditem object contains information about the parent object. use these methods to complete these tasks. post to yourself this code posts a feed item to the context user. the subjectid specifies me, which is an alias for the context user’s id. it could also specify the context user’s id. connectapi.feedelement feedelement = connectapi.chatterfeeds.postfeedelement(null, 'me', connectapi.feedelementtype.feeditem, 'working from home today.'); the parent property of the newly posted feed item contains the connectapi.usersummary of the context user. post to another user this code posts a feed item to a user other than the context user. the subjectid specifies the user id of the target user. connectapi.feedelement feedelement = connectapi.chatterfeeds.postfeedelement(null, '005d00000016qxp', connectapi.feedelementtype.feeditem, 'kevin, do you have information about the new categories?'); the parent property of the newly posted feed item contains the connectapi.usersummary of the target user. post to a group this code posts a feed item to a group. the subjectid specifies the group id. connectapi.feediteminput feediteminput = new connectapi.feediteminput(); connectapi.mentionsegmentinput mentionsegmentinput = new connectapi.mentionsegmentinput(); connectapi.messagebodyinput messagebodyinput = new connectapi.messagebodyinput(); 397apex developer guide using salesforce features with apex connectapi.textsegmentinput textsegmentinput = new connectapi.textsegmentinput(); messagebodyinput.messagesegments = new list<connectapi.messagesegmentinput>(); mentionsegmentinput.id = '005rr000000dme9'; messagebodyinput.messagesegments.add(mentionsegmentinput); textsegmentinput.text = 'could you take a look?'; messagebodyinput.messagesegments.add(textsegmentinput); feediteminput.body = messagebodyinput; feediteminput.feedelementtype = connectapi.feedelementtype.feeditem; feediteminput.subjectid = '0f9rr0000004cpw'; connectapi.feedelement feedelement = connectapi.ch
atterfeeds.postfeedelement(network.getnetworkid(), feediteminput); the parent property of the newly posted feed item contains the connectapi.chattergroupsummary of the specified group. post to a record (such as a file or an account) this code posts a feed item to a record and mentions a group. the subjectid specifies the record id. connectapi.feediteminput feediteminput = new connectapi.feediteminput(); connectapi.mentionsegmentinput mentionsegmentinput = new connectapi.mentionsegmentinput(); connectapi.messagebodyinput messagebodyinput = new connectapi.messagebodyinput(); connectapi.textsegmentinput textsegmentinput = new connectapi.textsegmentinput(); messagebodyinput.messagesegments = new list<connectapi.messagesegmentinput>(); textsegmentinput.text = 'does anyone know anyone with contacts here?'; messagebodyinput.messagesegments.add(textsegmentinput); // mention a group. mentionsegmentinput.id = '0f9d00000000oot'; messagebodyinput.messagesegments.add(mentionsegmentinput); feediteminput.body = messagebodyinput; feediteminput.feedelementtype = connectapi.feedelementtype.feeditem; // use a record id for the subject id. feediteminput.subjectid = '001d000000jvwl9'; connectapi.feedelement feedelement = connectapi.chatterfeeds.postfeedelement(null, feediteminput); the parent property of the new feed item depends on the record type specified in subjectid. if the record type is file, the parent is connectapi.filesummary. if the record type is group, the parent is connectapi.chattergroupsummary. if the record type is user, the parent is connectapi.usersummary. for all other record types, as in this example that uses an account, the parent is connectapi.recordsummary. get feed elements from a feed tip: to return a feed that includes feed elements, call these methods. feed element types include feed item, bundle, and recommendation. 398apex developer guide using salesforce features with apex getting feed items from a feed is similar, but not identical, for each feed type. get feed elements from the company, directmessagemoderation, directmessages, home, moderation, and pendingreview feeds to get the feed elements from these feeds, use these methods that don’t require a subjectid. • getfeedelementsfromfeed(communityid, feedtype) • getfeedelementsfromfeed(communityid, feedtype, pageparam, pagesize, sortparam) • getfeedelementsfromfeed(communityid, feedtype, recentcommentcount, density, pageparam, pagesize, sortparam) • getfeedelementsfromfeed(communityid, feedtype, recentcommentcount, density, pageparam, pagesize, sortparam, filter) • getfeedelementsfromfeed(communityid, feedtype, recentcommentcount, density, pageparam, pagesize, sortparam, filter, threadedcommentscollapsed) get feed elements from the favorites feed to get the feed elements from the favorites feed, specify a favoriteid. for these feeds, the subjectid must be the id of the context user or the alias me. • getfeedelements(communityid, subjectid, favoriteid) • getfeedelements(communityid, subjectid, favoriteid, pageparam, pagesize, sortparam) • getfeedelements(communityid, subjectid, favoriteid, recentcommentcount, elementsperbundle, pageparam, pagesize, sortparam) get feed elements from the filter feed to get the feed elements from the filters feed, specify a keyprefix. the keyprefix indicates the object type and is the first three characters of the object id. the subjectid must be the id of the context user or the alias me. • getfeedelementsfromfilterfeed(communityid, subjectid, keyprefix) • getfeedelementsfromfilterfeed(communityid, subjectid, keyprefix, pageparam, pagesize, sortparam) • getfeedelementsfromfilterfeed(communityid, subjectid, keyprefix, recentcommentcount, elementsperbundle, density, pageparam, pagesize, sortparam) get feed elements from the bookmarks, files, groups, mute, news, people, record, streams,
to, topics, and userprofile feeds to get the feed elements from these feed types, specify a subject id. if feedtype is record, subjectid can be any record id, including a group id. if feedtype is streams, subjectid must be a stream id. if feedtype is topics, subjectid must be a topic id. if feedtype is userprofile, subjectid can be any user id. if the feedtype is any other value, subjectid must be the id of the context user or the alias me. • getfeedelementsfromfeed(communityid, feedtype, subjectid) • getfeedelementsfromfeed(communityid, feedtype, subjectid, pageparam, pagesize, sortparam) • getfeedelementsfromfeed(communityid, feedtype, subjectid, recentcommentcount, density, pageparam, pagesize, sortparam) • getfeedelementsfromfeed(communityid, feedtype, subjectid, recentcommentcount, density, pageparam, pagesize, sortparam, filter) • getfeedelementsfromfeed(communityid, feedtype, subjectid, recentcommentcount, density, pageparam, pagesize, sortparam, filter, threadedcommentscollapsed) 399apex developer guide using salesforce features with apex get feed elements from a record feed for subjectid, specify a record id. tip: the record can be a record of any type that supports feeds, including group. the feed on the group page in the salesforce ui is a record feed. • getfeedelementsfromfeed(communityid, feedtype, subjectid, recentcommentcount, density, pageparam, pagesize, sortparam, showinternalonly) • getfeedelementsfromfeed(communityid, feedtype, subjectid, recentcommentcount, density, pageparam, pagesize, sortparam, customfilter) • getfeedelementsfromfeed(communityid, feedtype, subjectid, recentcommentcount, elementsperbundle, density, pageparam, pagesize, sortparam, showinternalonly) • getfeedelementsfromfeed(communityid, feedtype, subjectid, recentcommentcount, elementsperbundle, density, pageparam, pagesize, sortparam, showinternalonly, filter) • getfeedelementsfromfeed(communityid, feedtype, subjectid, recentcommentcount, elementsperbundle, density, pageparam, pagesize, sortparam, showinternalonly, customfilter) • getfeedelementsfromfeed(communityid, feedtype, subjectid, recentcommentcount, elementsperbundle, density, pageparam, pagesize, sortparam, showinternalonly, filter, threadedcommentscollapsed) • getfeedelementsfromfeed(communityid, feedtype, subjectid, recentcommentcount, elementsperbundle, density, pageparam, pagesize, sortparam, showinternalonly, customfilter, threadedcommentscollapsed) see also: apex reference guide: chatterfavorites class apex reference guide: chatterfeeds class apex reference guide: connectapi output classes apex reference guide: connectapi input classes accessing connectapi data in experience cloud sites many connectapi methods work within the context of a single experience cloud site. many connectapi methods include communityid as the first argument. if you don’t have digital experiences enabled, use internal or null for this argument. if you have digital experiences enabled, the communityid argument specifies whether to execute a method in the context of the default experience cloud site (by specifying internal or null) or in the context of a specific site (by specifying an id). any entity, such as a comment or a feed item, referred to by other arguments in the method must be in the specified site. the id is included in urls returned in the output. some connectapi methods include siteid as an argument. unlike communityid, if you don’t have digital experiences enabled, you can’t use these methods. the site id is included in urls returned in the output. most urls returned in connectapi output objects are connect rest api resources. if you specify an id, urls returned in the output use the following format: /connect/communities/communityid/resource 400apex developer guide using salesforce features with apex if you specify internal, urls returned in the output use the same format: /connect/communities/internal/resource if you specify null, urls returned in the output use one of these formats: /chatter/resource /connect/resource methods available to experience
cloud guest users if your experience cloud site allows access without logging in, guest users have access to many apex methods. these methods return information the guest user has access to. all overloads of these methods are available to guest users. important: if an overload of a method listed here indicates that chatter is required, you must also enable public access to your experience cloud site to make the method available to guest users. if you don’t enable public access, data retrieved by methods that require chatter doesn’t load correctly on public site pages. • announcements methods: – getannouncements() • chatterfeeds methods: – getcomment() – getcommentincontext() – getcommentsforfeedelement() – getextensions() – getfeed() – getfeedelement() – getfeedelementbatch() – getfeedelementpoll() – getfeedelementsfromfeed() – getfeedelementsupdatedsince() – getfeedwithfeedelements() – getlike() – getlikesforcomment() – getlikesforfeedelement() – getlinkmetadata() – getpinnedfeedelementsfromfeed() – getrelatedposts() – getthreadsforfeedcomment() – getvotesforcomment() – getvotesforfeedelement() – searchfeedelements() – searchfeedelementsinfeed() 401apex developer guide using salesforce features with apex – updatepinnedfeedelements() • chattergroups methods: – getgroup() – getgroups() – getmembers() – searchgroups() • chatterusers methods: – getfollowers() – getfollowings() – getreputation() – getuser() – getuserbatch() – getusergroups() – getusers() – searchusergroupdetails() – searchusers() • commercecart methods: – additemstocart() – additemtocart() – applycartcoupon() – copycarttowishlist() – createcart() – deletecart() – deletecartcoupon() – deletecartitem() – deleteinventoryreservation() (developer preview) – getcartcoupons() – getcartitems() – getcartsummary() – getorcreateactivecartsummary() – makecartprimary() – setcartmessagesvisibility() – updatecartitem() – upsertinventoryreservation() (developer preview) • commercecatalog methods: – getproduct() – getproductcategory() – getproductcategorychildren() 402apex developer guide using salesforce features with apex – getproductcategorypath() – getproductchildcollection() • commercepromotions methods: – decreaseredemption() – evaluate() – increaseredemption() • commercesearch methods: – getsortrules() – getsuggestions() – searchproducts() • commercestorepricing methods: – getproductprice() – getproductprices() • communities methods: – getcommunity() • employeeprofiles methods: – getphoto() • knowledge methods: – gettopviewedarticlesfortopic() – gettrendingarticles() – gettrendingarticlesfortopic() • managedcontent methods: – getallcontent() – getalldeliverychannels() – getallmanagedcontent() – getcontentbycontentkeys() – getcontentbyids() – getmanagedcontentbycontentkeys() – getmanagedcontentbyids() – getmanagedcontentbytopics() – getmanagedcontentbytopicsandcontentkeys() – getmanagedcontentbytopicsandids() • managedcontentdelivery methods: – getcollectionitemsforchannel() – getcollectionitemsforsite() – getmanagedcontentchannel() – getmanagedcontentforchannel() 403apex developer guide using salesforce features with apex – getmanagedcontentforsite() – getmanagedcontentsforchannel() – getmanagedcontentsforsite() • managedtopics methods: – getmanagedtopic() – getmanagedtopics() • marketingintegration methods: – submitform() • navigationmenu methods: – getcommunitynavigationmenu() • nextbestactions methods: – executestrategy() – setrecommendationreaction() • personalization methods: – getaudience() – getaudiencebatch() – getaudiences() – gettarget() – gettargetbatch() – gettargets() • recommend
ations methods: – getrecommendationsforuser() note: only article and file recommendations are available to guest users. • sites methods: – searchsite() • topics methods: – getgroupsrecentlytalkingabouttopic() – getrecentlytalkingabouttopicsforgroup() – getrecentlytalkingabouttopicsforuser() – getrelatedtopics() – gettopic() – gettopics() – gettrendingtopics() • userprofiles methods: 404apex developer guide using salesforce features with apex – getphoto() see also: salesforce help: give secure access to unauthenticated users with the guest user profile supported validations for dbt segments when creating or updating a segment, the connectapi.cdpsegmentinput class is subject to some sql validations. you can create a segment using the createsegment(input) method with the connectapi.cdpsegmentinput class. similarly, you can update a segment using the updatesegment(segmentapiname, input) method with the same input class. the connectapi.cdpsegmentdbtmodelinput input class, which is nested in the connectapi.cdpsegmentinput class, provides validation for the sql. the sql property of the connectapi.cdpsegmentdbtmodelinput is subject to these validations. • only the primary key of the segmenton dmo is allowed in the select statement. the first table in the join clause must be a profile table. – no aggregation (min, max, avg, count) is allowed at the top-level select. ---fail select max(individual_dense_viv__dlm.age__c) from individual_dense_viv__dlm ---fail select count(individual_dense_viv__dlm.individualid__c) from individual_dense_viv__dlm --- – no select all (*) expression is allowed in the top-level select. ---fail select * from individual_dense_viv__dlm – only the primary key of the segment on table (the first table in the from clause of the sql statement) is allowed to be selected. ---pass select individual_dense_viv__dlm.individualid__c from individual_dense_viv__dlm – multiple columns can’t be selected even if one of them is the primary key of the table. ---fail select individual_dense_viv__dlm.individualid__c, individual_dense_viv__dlm.age__c from individual_dense_viv__dlm – no case statements are allowed in the primary select. ---fail select case when individual_dense_viv__dlm.individualid__c > 10 then individual_dense_viv__dlm.individualid__c else null end from individual_dense_viv__dlm 405apex developer guide using salesforce features with apex • all columns must be fully qualified by tablename in the query and subselect queries. ---fail select individualid__c from individual_dense_viv__dlm • subqueries are supported only in a where clause and must emit only one column. ---fail select individual_dense_viv__dlm.individualid__c from (select * from individual_dense_viv__dlm) • limit and offset are supported. ---fail select individual_dense_viv__dlm.individualid__c from individual_dense_viv__dlm limit 10 • any sql statement other than the select statement isn’t allowed. ---fail update individual_dense_viv__dlm set individual_dense_viv__dlm.individualid__c = 'aa' using connectapi input and output classes some classes in the connectapi namespace contain static methods that access connect rest api data. the connectapi namespace also contains input classes to pass as parameters and output classes that calls to the static methods return. connectapi methods take either simple or complex types. simple types are primitive apex data like integers and strings. complex types are connectapi input objects. the successful execution of a connectapi method can return an output object from the connectapi namespace. connectapi output objects can be made up of other output objects. for example, the connectapi.actorwithid output object contains properties such as id and url, which contain primitive data types. it
also contains a mysubscription property, which contains a connectapi.reference object. note: all salesforce ids in connectapi output objects are 18 character ids. input objects can use 15 character ids or 18 character ids. see also: apex reference guide: connectapi input classes apex reference guide: connectapi output classes understanding limits for connectapi classes limits for methods in the connectapi namespace are different than the limits for other apex classes. for classes in the connectapi namespace, every write operation costs one dml statement against the apex governor limit. connectapi method calls are also subject to rate limiting. connectapi rate limits match connect rest api rate limits. both have a per user, per namespace, per hour rate limit. when you exceed the rate limit, a connectapi.ratelimitexception is thrown. your apex code must catch and handle this exception. when testing code, a call to the apex test.starttest method starts a new rate limit count. a call to the test.stoptest method sets your rate limit count to the value it was before you called test.starttest. 406apex developer guide using salesforce features with apex packaging connectapi classes if you include connectapi classes in a package, be aware of chatter dependencies. if a connectapi class has a dependency on chatter, the code can be compiled and installed in orgs that don’t have chatter enabled. however, if chatter isn’t enabled, the code throws an error at run time. system.noaccessexception: insufficient privileges: this feature is not currently enabled for this user. in its reference documentation, every connectapi method indicates whether or not it supports chatter. see also: distributing apex using managed packages serializing and deserializing connectapi objects when connectapi output objects are serialized into json, the structure is similar to the json returned from connect rest api. when connectapi input objects are deserialized from json, the format is also similar to connect rest api. connect in apex supports serialization and deserialization in these apex contexts. • json and jsonparser classes—serialize connect in apex outputs to json and deserialize connect in apex inputs from json. • apex rest with @restresource—serialize connect in apex outputs to json as return values and deserialize connect in apex inputs from json as parameters. • javascript remoting with @remoteaction—serialize connect in apex outputs to json as return values and deserialize connect in apex inputs from json as parameters. connect in apex follows these rules for serialization and deserialization. • only output objects can be serialized. • only top-level input objects can be deserialized. • enum values and exceptions cannot be serialized or deserialized. connectapi versioning and equality checking versioning in connectapi classes follows specific rules that are different than the rules for other apex classes. versioning for connectapi classes follows these rules. • a connectapi method call executes in the context of the version of the class that contains the method call. the use of version is analogous to the /vxx.x section of a connect rest api url. • each connectapi output object exposes a getbuildversion method. this method returns the version under which the method that created the output object was invoked. • when interacting with input objects, apex can access only properties supported by the version of the enclosing apex class. • input objects passed to a connectapi method may contain only non-null properties that are supported by the version of the apex class executing the method. if the input object contains version-inappropriate properties, an exception is thrown. • the output of the tostring method only returns properties that are supported in the version of the code interacting with the object. for output objects, the returned properties must also be supported in the build version. • apex rest, json.serialize, and @remoteaction serialization include only version-appropriate properties. • apex rest, json.deserialize, and @remoteaction deserialization reject properties that are version-inappropriate. • enums are not versioned. enum values are returned in all api versions. clients should handle values they don't understand gracefully. 407apex developer guide using salesforce features with apex equality checking for connectapi classes follows these rules. • input objects—properties are compared. • output objects—properties and build versions are compared. for example, if two objects have the same properties with the same values but have different build versions, the objects are not equal. to get
the build version, call getbuildversion. casting connectapi objects it may be useful to downcast some connectapi output objects to a more specific type. this technique is especially useful for message segments, feed item capabilities, and record fields. message segments in a feed item are typed as connectapi.messagesegment. feed item capabilities are typed as connectapi.feeditemcapability. record fields are typed as connectapi.abstractrecordfield. these classes are all abstract and have several concrete subclasses. at runtime you can use instanceof to check the concrete types of these objects and then safely proceed with the corresponding downcast. when you downcast, you must have a default case that handles unknown subclasses. the following example downcasts a connectapi.messagesegment to a connectapi.mentionsegment: if(segment instanceof connectapi.mentionsegment) { connectapi.mentionsegment = (connectapi.mentionsegment)segment; } important: the composition of a feed can change between releases. write your code to handle instances of unknown subclasses. see also: apex reference guide: chatterfeeds class apex reference guide: connectapi.feedelementcapabilities apex reference guide: connectapi.messagesegment apex reference guide: connectapi.abstractrecordview wildcards use wildcard characters to match text patterns in connect rest api and connect in apex searches. a common use for wildcards is searching a feed. pass a search string and wildcards in the q parameter. this example is a connect rest api request: /chatter/feed-elements?q=chat* this example is a connect in apex method call: connectapi.chatterfeeds.searchfeedelements(null, 'chat*'); you can specify the following wildcard characters to match text patterns in your search: wildcard description * asterisks match zero or more characters at the middle or end of your search term. for example, a search for john* finds items that start with john, such as, john, johnson, or johnny. a search for mi* meyers finds items with mike meyers or michael meyers. if you are searching for a literal asterisk in a word or phrase, then escape the asterisk (precede it with the \ character). 408apex developer guide using salesforce features with apex wildcard description ? question marks match only one character in the middle or end of your search term. for example, a search for jo?n finds items with the term john or joan but not jon or johan. you can't use a ? in a lookup search. when using wildcards, consider the following notes: • the more focused your wildcard search, the faster the search results are returned, and the more likely the results will reflect your intention. for example, to search for all occurrences of the word prospect (or prospects, the plural form), it is more efficient to specify prospect* in the search string than to specify a less restrictive wildcard search (such as prosp*) that could return extraneous matches (such as prosperity). • tailor your searches to find all variations of a word. for example, to find property and properties, you would specify propert*. • punctuation is indexed. to find * or ? inside a phrase, you must enclose your search string in quotation marks and you must escape the special character. for example, "where are you\?" finds the phrase where are you?. the escape character (\) is required in order for this search to work correctly. testing connectapi code like all apex code, connect in apex code requires test coverage. connect in apex methods don’t run in system mode, they run in the context of the current user (also called the context user). the methods have access to whatever the context user has access to. connect in apex doesn’t support the runas system method. most connect in apex methods require access to real organization data, and fail unless used in test methods marked @istest(seealldata=true). however, some connect in apex methods, such as getfeedelementsfromfeed, are not permitted to access organization data in tests and must be used with special test methods that register outputs to be returned in a test context. if a method requires a settest method, the requirement is stated in the method’s “usage” section. a test method name is the regular method name with a settest prefix. the test method signature (combination of parameters) matches a signature of the
regular method. for example, if the regular method has three overloads, the test method has three overloads. using connect in apex test methods is similar to testing web services in apex. first, build the data you expect the method to return. to build data, create output objects and set their properties. to create objects, you can use no-argument constructors for any non-abstract output classes. after you build the data, call the test method to register the data. call the test method that has the same signature as the regular method you’re testing. after you register the test data, run the regular method. when you run the regular method, the registered data is returned. important: use the test method signature that matches the regular method signature. if data wasn't registered with the matching set of parameters when you call the regular method, you receive an exception. this example shows a test that constructs an connectapi.feedelementpage and registers it to be returned when getfeedelementsfromfeed is called with a particular combination of parameters. global class newsfeedclass { global static integer getnewsfeedcount() { connectapi.feedelementpage elements = connectapi.chatterfeeds.getfeedelementsfromfeed(null, connectapi.feedtype.news, 'me'); return elements.elements.size(); 409apex developer guide using salesforce features with apex } } @istest private class newsfeedclasstest { @istest static void dotest() { // build a simple feed item connectapi.feedelementpage testpage = new connectapi.feedelementpage(); list<connectapi.feeditem> testitemlist = new list<connectapi.feeditem>(); testitemlist.add(new connectapi.feeditem()); testitemlist.add(new connectapi.feeditem()); testpage.elements = testitemlist; // set the test data connectapi.chatterfeeds.settestgetfeedelementsfromfeed(null, connectapi.feedtype.news, 'me', testpage); // the method returns the test page, which we know has two items in it. test.starttest(); system.assertequals(2, newsfeedclass.getnewsfeedcount()); test.stoptest(); } } differences between connectapi classes and other apex classes note these additional differences between connectapi classes and other apex classes. system mode and context user connect in apex methods don’t run in system mode, they run in the context of the current user (also called the context user). the methods have access to whatever the context user has access to. connect in apex doesn’t support the runas system method. when a method takes a subjectid argument, often that subject must be the context user. in these cases, you can use the string me to specify the context user instead of an id. connect in apex isn’t available to automated process users by default. connect in apex is available to these users: • chatter-only users • guest users • portal users • standard users with sharing and without sharing connect in apex ignores the with sharing and without sharing keywords. instead, the context user controls all security, field level sharing, and visibility. for example, if the context user is a member of a private group, connectapi classes can post to that group. if the context user is not a member of a private group, the code can’t see the feed items for that group and can’t post to the group. asynchronous operations some connect in apex operations are asynchronous, that is, they don’t occur immediately. for example, if your code adds a feed item for a user, it isn’t immediately available in the news feed. another example: when you add a photo, it’s not available immediately. for testing, if you add a photo, you can’t retrieve it immediately. 410apex developer guide using salesforce features with apex no xml support in apex rest apex rest doesn’t support xml serialization and deserialization of connect in apex objects. apex rest does support json serialization and deserialization of connect in apex objects. empty log entries information about connect in apex objects doesn’t appear in variable_assignment log events. no apex soap web services support connect in apex objects can’t be used in apex soap web services indicated with the keyword webservice. moderate chatter private messages with triggers write a trigger for chattermessage
to automate the moderation of private messages in an org or editions experience cloud site. use triggers to ensure that messages conform to your company’s messaging policies and don’t contain blocklisted words. available in: salesforce write an apex before insert trigger to review the private message body and information about the classic sender. you can add validation messages to the record or the body field, which causes the message available in: enterprise, to fail and an error to be returned to the user. performance, unlimited, although you can create an after insert trigger, chattermessage is not updatable, and consequently and developer editions any after insert trigger that modifies chattermessage will fail at run time with an appropriate error message. user permissions to create a trigger for private messages from setup, enter chattermessage triggers in the quick find box, then select chattermessage triggers. alternatively, you can create a to save apex triggers for chattermessage: trigger from the developer console by clicking file > new > apex trigger and selecting • author apex chattermessage from the sobject drop-down list. and this table lists the fields that are exposed on chattermessage. manage chatter table 8: available fields in chattermessage messages and direct messages field apex data type description id id unique identifier for the chatter message body string body of the chatter message as posted by the sender senderid id user id of the sender sentdate datetime date and time that the message was sent sendingnetworkid id network (site) in which the message was sent. this field is visible only if digital experiences is enabled and private messages is enabled in at least one site. this example shows a before insert trigger on chattermessage that is used to review each new message. this trigger calls a class method, moderator.review(), to review each new message before it is inserted. trigger privatemessagemoderationtrigger on chattermessage (before insert) { chattermessage[] messages = trigger.new; 411apex developer guide using salesforce features with apex // instantiate the message moderator using the factory method messagemoderator moderator = messagemoderator.getinstance(); for (chattermessage currentmessage : messages) { moderator.review(currentmessage); } } if a message violates your policy, for example when the message body contains blocklisted words, you can prevent the message from being sent by calling the apex adderror method. you can call adderror to add a custom error message on a field or on the entire message. the following snippet shows a portion of the reviewcontent method that adds an error to the message body field. if (proposedmsg.contains(nextblocklistedword)) { themessage.body.adderror( 'this message does not conform to the acceptable use policy'); system.debug('moderation flagged message with word: ' + nextblocklistedword); problemsfound=true; break; } the following is the full messagemoderator class, which contains methods for reviewing the sender and the content of messages. part of the code in this class has been deleted for brevity. public class messagemoderator { private static list<string> blocklistedwords=null; private static messagemoderator instance=null; /** overall review includes checking the content of the message, and validating that the sender is allowed to send messages. **/ public void review(chattermessage themessage) { reviewcontent(themessage); reviewsender(themessage); } /** this method is used to review the content of the message. if the content is unacceptable, field level error(s) are added. **/ public void reviewcontent(chattermessage themessage) { // forcing to lower case for matching string proposedmsg=themessage.body.tolowercase(); boolean problemsfound=false; // assume it's acceptable // iterate through the blocklist looking for matches for (string nextblocklistedword : blocklistedwords) { if (proposedmsg.contains(nextblocklistedword)) { themessage.body.adderror( 'this message does not conform to the acceptable use policy'); system.debug('moderation flagged message with word: ' + nextblocklistedword); problemsfound=true; break; 412apex developer guide using salesforce features with apex } } // for demo purposes, we're going to add a "seal of approval" to the
// message body which is visible. if (!problemsfound) { themessage.body = themessage.body + ' *** approved, meets conduct guidelines'; } } /** is the sender allowed to send messages in this context? -- moderators -- always allowed to send -- internal members -- always allowed to send -- site members -- in general only allowed to send if they have a sufficient reputation -- site members -- with insufficient reputation may message the moderator(s) **/ public void reviewsender(chattermessage themessage) { // are we in a site context? boolean issitecontext = (themessage.sendingnetworkid != null); // get the user user sendinguser = [select id, name, usertype, isportalenabled from user where id = :themessage.senderid ]; // ... } /** enforce a singleton pattern to improve performance **/ public static messagemoderator getinstance() { if (instance==null) { instance = new messagemoderator(); } return instance; } /** default contructor is private to prevent others from instantiating this class without using the factory. initializes the static members. **/ private messagemoderator() { initializeblocklist(); } /** helper method that does the "heavy lifting" to load up the dictionaries from the database. should only run once to initialize the static member which is used for 413apex developer guide using salesforce features with apex subsequent validations. **/ private void initializeblocklist() { if (blocklistedwords==null) { // fill list of blocklisted words // ... } } } dataweave in apex (beta) dataweave in apex uses the mulesoft dataweave library to read and parse data from one format, transform it, and export it in a different format. you can create dataweave scripts as metadata and invoke them directly from apex. like apex, dataweave scripts are run within salesforce application servers, enforcing the same heap and cpu limits on the executing code. note: this feature is a beta service. customer may opt to try such beta service in its sole discretion. any use of the beta service is subject to the applicable beta services terms provided at agreements and terms. you can provide feedback and suggestions for the dataweave in apex feature in the trailblazer community. the beta release of dataweave in apex supports packaging of dataweave scripts within a namespace. however, you can only access scripts within a package, not across different namespaces. enterprise applications often require transformation of data between formats such as csv, json, xml, and apex objects. dataweave in apex complements native apex support for json and xml processing, and makes data transformation easier to code, more scalable, and efficient. apex developers can focus more on solving business problems and less on addressing the specifics of file formats. dataweave is the mulesoft expression language for accessing, parsing, and transforming data that travels through a mule application. for detailed information, see dataweave overview. note: you don’t have to be a mulesoft customer or have any specific salesforce license to use dataweave in apex. the following are some use-cases for dataweave in apex. • serializing apex objects with custom date formats • serializing and deserializing json with apex reserved keywords • performing custom transformations like removing or adding namespaces or removing __c suffixes • parsing and transforming rfc 4180 compliant csv (comma-separated values) data in this section: implementing dataweave in apex (beta) create dataweave scripts as metadata and invoke them directly from apex. use class methods and exceptions in the dataweave namespace to load and execute the scripts. examples of dataweave in apex (beta) here are code samples that demonstrate dataweave in apex. limitations of dataweave in apex (beta) dataweave in apex has these limitations in developer preview. see also: apex reference guide: dataweave namespace metadata api developer guide: dataweaveresource 414apex developer guide using salesforce features with apex implementing dataweave in apex (beta) create dataweave scripts as metadata and invoke them directly from apex. use class methods and exceptions in the dataweave namespace to load and execute the scripts. note: this feature is a beta service. customer may opt to try such beta service in its sole discretion. any use of the beta service
is subject to the applicable beta services terms provided at agreements and terms. you can provide feedback and suggestions for the dataweave in apex feature in the trailblazer community. the beta release of dataweave in apex supports packaging of dataweave scripts within a namespace. however, you can only access scripts within a package, not across different namespaces. dataweave namespace the dataweave namespace provides classes and methods to support the invocation of dataweave scripts from apex. the script class contains the createscript() method to load dataweave scripts from .dwl metadata files that have been deployed to an org. the resulting script can then be run with a payload using the execute() method to obtain script output in a dataweave.result object. the result class contains methods to retrieve script output using script class methods. for more information on these classes and methods, see dataweave namespace. for every dataweave script, an inner class of type dataweavescriptresource.scriptname is generated. the inner class extends the dataweave.script class. you can use the generated dataweavescriptresource.scriptname class instead of using the actual script name via the createscript() method. dataweave scripts that are currently being referenced via this inner class can't be deleted. to make the generated dataweavescriptresource class global, set the isglobal field in the dataweaveresource metadata object. <?xml version="1.0" encoding="utf-8"?> <dataweaveresource xmlns="http://soap.sforce.com/2006/04/metadata"> <apiversion>58.0</apiversion> <isglobal>true</isglobal> </dataweaveresource> the catchable system.dataweavescriptexception exception is available for error handling. runtime script exceptions that occur within dataweave are exposed to apex with this exception type. dataweave scripts support logging using the log(string, value) function. log messages that originate from dataweave are reflected in apex debug logs as dataweave_user_debug events, under the apex code log category at the debug log level. supporting information dataweave 2.4 script syntax is supported in apex, except for these limitations: limitations of dataweave in apex (beta). these tools support the development of dataweave scripts. • dataweave interactive learning is an online interactive playground that you can use to test your dataweave scripts. • dataweave 2.0 vscode marketplace extension adds code highlighting and other feature support for editing dataweave scripts. examples of dataweave in apex (beta) here are code samples that demonstrate dataweave in apex. note: this feature is a beta service. customer may opt to try such beta service in its sole discretion. any use of the beta service is subject to the applicable beta services terms provided at agreements and terms. you can provide feedback and suggestions for the dataweave in apex feature in the trailblazer community. the beta release of dataweave in apex supports packaging of dataweave scripts within a namespace. however, you can only access scripts within a package, not across different namespaces. these are instructions to use dataweave in apex, with an associated example. 415apex developer guide using salesforce features with apex • create a dataweave script source file. for example: csvtocontacts.dwl. %dw 2.0 input records application/csv output application/apex --- records map(record) -> { firstname: record.first_name, lastname: record.last_name, email: record.email } as object {class: "contact"} • create the associated metadata file. for example: csvtocontacts.dwl-meta.xml. <?xml version="1.0" encoding="utf-8"?> <dataweaveresource xmlns="http://soap.sforce.com/2006/04/metadata"> <apiversion>58.0</apiversion> <isglobal>false</isglobal> </dataweaveresource> • push the source to the scratch org using salesforce cli version v7.151.9 or higher. see salesforce cli release notes. • invoke the dataweave script from apex and check the results from anonymous apex. this example invokes the csvtocontacts.dwl script. // csv data for contacts string inputcsv = 'first_name,last_name,email\ncodey,"the bear",[email protected]'; dataweave.script
dwscript = new dataweavescriptresource.csvtocontacts(); dataweave.result dwresult = dwscript.execute(new map<string, object>{'records' => inputcsv}); list<contact> results = (list<contact>)dwresult.getvalue(); assert.areequal(1, results.size()); contact codeycontact = results[0]; assert.areequal('codey',codeycontact.firstname); assert.areequal('the bear',codeycontact.lastname); note: extensive code samples that demonstrate the dataweave in apex feature are available on developerforce. limitations of dataweave in apex (beta) dataweave in apex has these limitations in developer preview. note: this feature is a beta service. customer may opt to try such beta service in its sole discretion. any use of the beta service is subject to the applicable beta services terms provided at agreements and terms. you can provide feedback and suggestions for the dataweave in apex feature in the trailblazer community. the beta release of dataweave in apex supports packaging of dataweave scripts within a namespace. however, you can only access scripts within a package, not across different namespaces. • the dataweave java bridge, that is, the ability to bind to static java methods is disabled. see introduction to mule 4. features that interact with the environment such as the readurl and envvar functions are also disabled. these checks are done at script creation time instead of at runtime. 416apex developer guide using salesforce features with apex • you must specify encoding for binary input (apex blobs) to be coerced to strings: binaryvariable as string {encoding: 'utf8' }". • dataweave is constrained to disallow the loading of additional libraries. therefore, scripts must be self-contained. • dataweave modules and importing other scripts aren’t supported. for example, import modules::mymapping as per using a mapping file in a dataweave script isn’t supported. note: the feature supports built-in modules. see dataweave reference. • dataweave in apex doesn’t support these content types. – flat file format (application/flatfile) – excel (application/xlsx) – arvo (application/avro) • apex classes must be at api version 53.0 or later to access dataweave integration methods. • there’s a maximum of 50 dataweave scripts per org. • the maximum body size of one dataweave script is 100000 (one hundred thousand) characters. note: xml entity expansion isn’t supported, either currently or in the future, as a guard against denial of service attacks. moderate feed items with triggers write a trigger for feeditem to automate the moderation of posts in an org or experience cloud editions site. use triggers to ensure that posts conform to your company’s communication policies and don’t contain unwanted words or phrases. available in: enterprise, write an apex before insert trigger to review the feed item body and change the status of the feed performance, unlimited, item if it contains a blocklisted phrase. to create a trigger for feed items from setup, enter and developer editions feeditem triggers in the quick find box, then select feeditem triggers. alternatively, you can create a trigger from the developer console by clicking file > new > apex trigger and user permissions selecting feeditem from the sobject drop-down list. to save apex triggers for this example shows a before insert trigger on feeditem that is used to review each new post. if the feeditem: post contains the unwanted phrase, the trigger also sets the status of the post to • author apex pendingreview. trigger reviewfeeditem on feeditem (before insert) { for (integer i = 0; i<trigger.new.size(); i++) { // we don't want to leak "test phrase" information. if (trigger.new[i].body.containsignorecase('test phrase')) { trigger.new[i].status = 'pendingreview'; system.debug('caught one for pendingreview'); } } } 417apex developer guide using salesforce features with apex experience cloud sites experience cloud sites are branded spaces for your employees, customers, and partners to connect. you can customize and create sites to meet your business needs, then transition seamlessly between them. interact with experience cloud sites in apex using the network class and using connect in
apex classes in the connectapi namespace. connect in apex has a connectapi.communities class with methods that return information about sites. many connect in apex methods take a communityid argument, and some connect in apex methods take a siteid argument see also: apex reference guide: network class apex reference guide: connect in apex email you can use apex to work with inbound and outbound email. use apex with these email features: in this section: inbound email use apex to work with email sent to salesforce. outbound email use apex to work with email sent from salesforce. inbound email use apex to work with email sent to salesforce. you can use apex to receive and process email and attachments. the email is received by the apex email service, and processed by apex classes that utilize the inboundemail object. note: the apex email service is only available in developer, enterprise, unlimited, and performance edition organizations. see apex email service. outbound email use apex to work with email sent from salesforce. you can use apex to send individual and mass email. the email can include all standard email attributes (such as subject line and blind carbon copy address), use salesforce email templates, and be in plain text or html format, or those generated by visualforce. note: visualforce email templates cannot be used for mass email. you can use salesforce to track the status of email in html format, including the date the email was sent, first opened and last opened, and the total number of times it was opened. to send individual and mass email with apex, use the following classes: 418apex developer guide using salesforce features with apex singleemailmessage instantiates an email object used for sending a single email message. the syntax is: messaging.singleemailmessage mail = new messaging.singleemailmessage(); massemailmessage instantiates an email object used for sending a mass email message. the syntax is: messaging.massemailmessage mail = new messaging.massemailmessage(); messaging includes the static sendemail method, which sends the email objects you instantiate with either the singleemailmessage or massemailmessage classes, and returns a sendemailresult object. the syntax for sending an email is: messaging.sendemail(new messaging.email[] { mail } , opt_allornone); where email is either messaging.singleemailmessage or messaging.massemailmessage. the optional opt_allornone parameter specifies whether sendemail prevents delivery of all other messages when any of the messages fail due to an error (true), or whether it allows delivery of the messages that don't have errors (false). the default is true. includes the static reservemassemailcapacity and reservesingleemailcapacity methods, which can be called before sending any emails to ensure that the sending organization doesn’t exceed its daily email limit when the transaction is committed and emails are sent. the syntax is: messaging.reservemassemailcapacity(count); and messaging.reservesingleemailcapacity(count); where count indicates the total number of addresses that emails will be sent to. note the following: • the email is not sent until the apex transaction is committed. • the email address of the user calling the sendemail method is inserted in the from address field of the email header. all email that is returned, bounced, or received out-of-office replies goes to the user calling the method. • maximum of 10 sendemail methods per transaction. use the limits methods to verify the number of sendemail methods in a transaction. • single email messages sent with the sendemail method count against the sending organization's daily single email limit. when this limit is reached, calls to the sendemail method using singleemailmessage are rejected, and the user receives a single_email_limit_exceeded error code. however, single emails sent through the application are allowed. • mass email messages sent with the sendemail method count against the sending organization's daily mass email limit. when this limit is reached, calls to the sendemail method using massemailmessage are rejected, and the user receives a mass_mail_limit_exceeded error code. • any error returned in the sendemailresult object indicates that no email was sent. messaging.singleemailmessage has a method called setorgwideemailaddressid. it accepts an object id to an orgwideemailaddress object. if setorgwideemailaddressid is passed a valid id, the orgwideemailaddress.displayname field is used in the email header, instead of the logged
-in user's display name. the sending email address in the header is also set to the field defined in orgwideemailaddress.address. 419apex developer guide using salesforce features with apex note: if both orgwideemailaddress.displayname and setsenderdisplayname are defined, the user receives a duplicate_sender_display_name error. for more information, see organization-wide email addresses in the salesforce help . example // first, reserve email capacity for the current apex transaction to ensure // that we won't exceed our daily email limits when sending email after // the current transaction is committed. messaging.reservesingleemailcapacity(2); // processes and actions involved in the apex transaction occur next, // which conclude with sending a single email. // now create a new single email message object // that will send out a single email to the addresses in the to, cc & bcc list. messaging.singleemailmessage mail = new messaging.singleemailmessage(); // strings to hold the email addresses to which you are sending the email. string[] toaddresses = new string[] {'[email protected]'}; string[] ccaddresses = new string[] {'[email protected]'}; // assign the addresses for the to and cc lists to the mail object. mail.settoaddresses(toaddresses); mail.setccaddresses(ccaddresses); // specify the address used when the recipients reply to the email. mail.setreplyto('[email protected]'); // specify the name used as the display name. mail.setsenderdisplayname('salesforce support'); // specify the subject line for your email address. mail.setsubject('new case created : ' + case.id); // set to true if you want to bcc yourself on the email. mail.setbccsender(false); // optionally append the salesforce email signature to the email. // the email address of the user executing the apex code will be used. mail.setusesignature(false); // specify the text content of the email. mail.setplaintextbody('your case: ' + case.id +' has been created.'); mail.sethtmlbody('your case:<b> ' + case.id +' </b>has been created.<p>'+ 'to view your case <a href=https://mydomainname.my.salesforce.com/'+case.id+'>click here.</a>'); // send the email you have created. messaging.sendemail(new messaging.singleemailmessage[] { mail }); 420apex developer guide using salesforce features with apex external services external services connect your salesforce org to a service outside of salesforce, such as an employee banking service. after you register the external service, you can call it natively in your apex code. objects and operations defined in the external service's registered api specification become apex classes and methods in the externalservice namespace. the registered service's schema types map to apex types, and are strongly typed, making the apex compiler do the heavy lifting for you. for example, you can make a type safe callout to an external service from apex without needing to use the http class or perform transforms on json strings. see also: salesforce help: invoke external service callouts using apex flows flow builder lets admins build applications, known as flows, that automate a business process by collecting data and doing something in your salesforce org or an external system. for example, you can create a flow to script calls for a customer support center or to generate real-time quotes for a sales team. you can embed a flow in a visualforce page or aura component and access it in an apex controller. in this section: getting flow variables you can retrieve flow variables for a specific flow in apex. making callouts to external systems from invocable actions when you define a method that runs as an invocable action in a screen flow and makes a callout to an external system, use the callout modifier. passing data to a flow using the process.plugin interface process.pluginis a built-in interface that lets you process data within your org and pass it to a specified flow. the interface exposes apex as a service, which accepts input values and returns output back to the flow. getting flow variables you can retrieve flow variables for a specific flow in apex. the flow.interview apex class provides the getvariablevalue method for retrieving a flow variable, which can be
in the flow embedded in the visualforce page, or in a separate flow that is called by a subflow element. this example shows how to use this method to obtain breadcrumb (navigation) information from the flow embedded in the visualforce page. if that flow contains subflow elements, and each of the referenced flows also contains a vabreadcrumb variable, the visualforce page can provide users with breadcrumbs regardless of which flow the interview is running. public class samplecontoller { // instance of the flow public flow.interview.flow_template_gallery myflow {get; set;} public string getbreadcrumb() { string abreadcrumb; if (myflow==null) { return 'home';} else abreadcrumb = (string) myflow.getvariablevalue('vabreadcrumb'); return(abreadcrumb==null ? 'home': abreadcrumb); 421apex developer guide using salesforce features with apex } } see also: apex reference guide: interview class making callouts to external systems from invocable actions when you define a method that runs as an invocable action in a screen flow and makes a callout to an external system, use the callout modifier. when the method is executed as an invocable action, screen flows use this modifier to determine whether the action can be executed safely in the current transaction. flow admins can configure the action to let flow decide whether to execute the action in a new transaction or the current one. when all of the following conditions are met, the flow commits the current transaction, starts a new transaction, and makes the call to an external system safely: • the method's callout modifier is true. • the action's transaction control setting in a screen flow is configured to let flow decide. • the current transaction has uncommitted work. if any of the following conditions are true, the flow executes the action in the current transaction: • the callout modifier is false. • the action is executed by a non-screen flow. • the current transaction doesn’t have uncommitted work. see also: invocablemethod annotation passing data to a flow using the process.plugin interface process.pluginis a built-in interface that lets you process data within your org and pass it to a specified flow. the interface exposes apex as a service, which accepts input values and returns output back to the flow. tip: we recommend using the @invocablemethod annotation instead of the process.plugin interface. • the interface doesn’t support blob, collection, sobject, and time data types, and it doesn’t support bulk operations. once you implement the interface on a class, the class can be referenced only from flows. • the annotation supports all data types and bulk operations. once you implement the annotation on a class, the class can be referenced from flows, processes, and the custom invocable actions rest api endpoint. when you define an apex class that implements the process.plugin interface in your org, it's available in flow builder as a legacy apex action. process.plugin has these top-level classes. • process.pluginrequest passes input parameters from the class that implements the interface to the flow. • process.pluginresult returns output parameters from the class that implements the interface to the flow. 422apex developer guide using salesforce features with apex • process.plugindescriberesult passes input parameters from a flow to the class that implements the interface. this class determines the input parameters and output parameters needed by the process.pluginresult plug-in. when you write apex unit tests, instantiate a class and pass it into the interface invoke method. to pass in the parameters that the system needs, create a map and use it in the constructor. for more information, see using the process.pluginrequest class on page 425. in this section: implementing the process.plugin interface process.plugin is a built-in interface that allows you to pass data between your organization and a specified flow. using the process.pluginrequest class the process.pluginrequest class passes input parameters from the class that implements the interface to the flow. using the process.pluginresult class the process.pluginresult class returns output parameters from the class that implements the interface to the flow. using the process.plugindescriberesult class use the process.plugin interface describe method to dynamically provide both input and output parameters for the flow. this method returns the process.plugindescriberesult class. process.plugin data type conversions understand how data types are converted between apex and the values returned to
the process.plugin. for example, text data in a flow converts to string data in apex. sample process.plugin implementation for lead conversion in this example, an apex class implements the process.plugin interface and converts a lead into an account, contact, and optionally, an opportunity. test methods for the plug-in are also included. this implementation can be called from a flow via a legacy apex action. implementing the process.plugin interface process.plugin is a built-in interface that allows you to pass data between your organization and a specified flow. tip: we recommend using the @invocablemethod annotation instead of the process.plugin interface. • the interface doesn’t support blob, collection, sobject, and time data types, and it doesn’t support bulk operations. once you implement the interface on a class, the class can be referenced only from flows. • the annotation supports all data types and bulk operations. once you implement the annotation on a class, the class can be referenced from flows, processes, and the custom invocable actions rest api endpoint. the class that implements the process.plugin interface must call these methods. name arguments return type description describe process.plugindescriberesult returns a process.plugindescriberesult object that describes this method call. invoke process.pluginrequest process.pluginresult primary method that the system invokes when the class that implements the interface is instantiated. 423apex developer guide using salesforce features with apex example implementation global class flowchat implements process.plugin { // the main method to be implemented. the flow calls this at runtime. global process.pluginresult invoke(process.pluginrequest request) { // get the subject of the chatter post from the flow string subject = (string) request.inputparameters.get('subject'); // use the chatter apis to post it to the current user's feed feeditem fitem = new feeditem(); fitem.parentid = userinfo.getuserid(); fitem.body = 'flow update: ' + subject; insert fitem; // return to flow map<string,object> result = new map<string,object>(); return new process.pluginresult(result); } // returns the describe information for the interface global process.plugindescriberesult describe() { process.plugindescriberesult result = new process.plugindescriberesult(); result.name = 'flowchatplugin'; result.tag = 'chat'; result.inputparameters = new list<process.plugindescriberesult.inputparameter>{ new process.plugindescriberesult.inputparameter('subject', process.plugindescriberesult.parametertype.string, true) }; result.outputparameters = new list<process.plugindescriberesult.outputparameter>{ }; return result; } } test class the following is a test class for the above class. @istest private class flowchattest { static testmethod void flowchattests() { flowchat plugin = new flowchat(); map<string,object> inputparams = new map<string,object>(); string feedsubject = 'flow is alive'; inputparams.put('subject', feedsubject); process.pluginrequest request = new process.pluginrequest(inputparams); 424apex developer guide using salesforce features with apex plugin.invoke(request); } } using the process.pluginrequest class the process.pluginrequest class passes input parameters from the class that implements the interface to the flow. tip: we recommend using the @invocablemethod annotation instead of the process.plugin interface. • the interface doesn’t support blob, collection, sobject, and time data types, and it doesn’t support bulk operations. once you implement the interface on a class, the class can be referenced only from flows. • the annotation supports all data types and bulk operations. once you implement the annotation on a class, the class can be referenced from flows, processes, and the custom invocable actions rest api endpoint. this class has no methods. constructor signature: process.pluginrequest (map<string,object>) here’s an example of instantiating the process.pluginrequest class with one input parameter. map<string,object> inputparams = new map<string,object>(); string feedsubject = 'flow is alive'; inputparams.put('subject', feedsubject); process.pluginrequest request = new process.pluginrequest(inputparams); code example in this example, the code returns
the subject of a chatter post from a flow and posts it to the current user's feed. global process.pluginresult invoke(process.pluginrequest request) { // get the subject of the chatter post from the flow string subject = (string) request.inputparameters.get('subject'); // use the chatter apis to post it to the current user's feed feedpost fpost = new feedpost(); fpost.parentid = userinfo.getuserid(); fpost.body = 'flow update: ' + subject; insert fpost; // return to flow map<string,object> result = new map<string,object>(); return new process.pluginresult(result); } // describes the interface global process.plugindescriberesult describe() { process.plugindescriberesult result = new process.plugindescriberesult(); result.inputparameters = new list<process.plugindescriberesult.inputparameter>{ new process.plugindescriberesult.inputparameter('subject', process.plugindescriberesult.parametertype.string, true) 425apex developer guide using salesforce features with apex }; result.outputparameters = new list<process.plugindescriberesult.outputparameter>{ }; return result; } } using the process.pluginresult class the process.pluginresult class returns output parameters from the class that implements the interface to the flow. tip: we recommend using the @invocablemethod annotation instead of the process.plugin interface. • the interface doesn’t support blob, collection, sobject, and time data types, and it doesn’t support bulk operations. once you implement the interface on a class, the class can be referenced only from flows. • the annotation supports all data types and bulk operations. once you implement the annotation on a class, the class can be referenced from flows, processes, and the custom invocable actions rest api endpoint. you can instantiate the process.pluginresult class using one of the following formats: • process.pluginresult (map<string,object>) • process.pluginresult (string, object) use the map when you have more than one result or when you don't know how many results will be returned. the following is an example of instantiating a process.pluginresult class. string url = 'https://docs.google.com/document/edit?id=abc'; string status = 'success'; map<string,object> result = new map<string,object>(); result.put('url', url); result.put('status',status); new process.pluginresult(result); using the process.plugindescriberesult class use the process.plugin interface describe method to dynamically provide both input and output parameters for the flow. this method returns the process.plugindescriberesult class. tip: we recommend using the @invocablemethod annotation instead of the process.plugin interface. • the interface doesn’t support blob, collection, sobject, and time data types, and it doesn’t support bulk operations. once you implement the interface on a class, the class can be referenced only from flows. • the annotation supports all data types and bulk operations. once you implement the annotation on a class, the class can be referenced from flows, processes, and the custom invocable actions rest api endpoint. the process.plugindescriberesult class doesn’t support the following functions. • queries • data modification • email • apex nested callouts 426apex developer guide using salesforce features with apex process.plugindescriberesult class and subclass properties here’s the constructor for the process.plugindescriberesult class. process.plugindescriberesult classname = new process.plugindescriberesult(); • plugindescriberesult class properties • plugindescriberesult.inputparameter class properties • plugindescriberesult.outputparameter class properties here’s the constructor for the process.plugindescriberesult.inputparameter class. process.plugindescriberesult.inputparameter ip = new process.plugindescriberesult.inputparameter(name,optional_description_string, process.plugindescriberesult.parametertype.enum, boolean_required); here’s the constructor for the process.plugindescriberesult.outputparameter class. process.plugindescriberesult.outputparameter op = new new process.plugindescriberesult.outputparameter(name,optional description string, process.plugindescriberesult.parametertype.enum); to use the process.plugindescriberesult class, create instances of these
subclasses. • process.plugindescriberesult.inputparameter • process.plugindescriberesult.outputparameter process.plugindescriberesult.inputparameter is a list of input parameters and has the following format. process.plugindescriberesult.inputparameters = new list<process.plugindescriberesult.inputparameter>{ new process.plugindescriberesult.inputparameter(name,optional_description_string, process.plugindescriberesult.parametertype.enum, boolean_required) for example: process.plugindescriberesult result = new process.plugindescriberesult(); result.setdescription('this plugin gets the name of a user'); result.settag ('userinfo'); result.inputparameters = new list<process.plugindescriberesult.inputparameter>{ new process.plugindescriberesult.inputparameter('fullname', process.plugindescriberesult.parametertype.string, true), new process.plugindescriberesult.inputparameter('dob', process.plugindescriberesult.parametertype.date, true), }; process.plugindescriberesult.outputparameter is a list of output parameters and has the following format. process.plugindescriberesult.outputparameters = new list<process.plugindescriberesult.outputparameter>{ new process.plugindescriberesult.outputparameter(name,optional description string, process.plugindescriberesult.parametertype.enum) for example: process.plugindescriberesult result = new process.plugindescriberesult(); result.setdescription('this plugin gets the name of a user'); 427apex developer guide using salesforce features with apex result.settag ('userinfo'); result.outputparameters = new list<process.plugindescriberesult.outputparameter>{ new process.plugindescriberesult.outputparameter('url', process.plugindescriberesult.parametertype.string), both classes take the process.plugindescriberesult.parametertype enum. valid values are: • boolean • date • datetime • decimal • double • float • id • integer • long • string for example: process.plugindescriberesult result = new process.plugindescriberesult(); result.outputparameters = new list<process.plugindescriberesult.outputparameter>{ new process.plugindescriberesult.outputparameter('url', process.plugindescriberesult.parametertype.string, true), new process.plugindescriberesult.outputparameter('status', process.plugindescriberesult.parametertype.string), }; process.plugin data type conversions understand how data types are converted between apex and the values returned to the process.plugin. for example, text data in a flow converts to string data in apex. tip: we recommend using the @invocablemethod annotation instead of the process.plugin interface. • the interface doesn’t support blob, collection, sobject, and time data types, and it doesn’t support bulk operations. once you implement the interface on a class, the class can be referenced only from flows. • the annotation supports all data types and bulk operations. once you implement the annotation on a class, the class can be referenced from flows, processes, and the custom invocable actions rest api endpoint. flow data type data type number decimal date datetime/date datetime datetime/date boolean boolean and numeric with 1 or 0 values only text string 428apex developer guide using salesforce features with apex sample process.plugin implementation for lead conversion in this example, an apex class implements the process.plugin interface and converts a lead into an account, contact, and optionally, an opportunity. test methods for the plug-in are also included. this implementation can be called from a flow via a legacy apex action. tip: we recommend using the @invocablemethod annotation instead of the process.plugin interface. • the interface doesn’t support blob, collection, sobject, and time data types, and it doesn’t support bulk operations. once you implement the interface on a class, the class can be referenced only from flows. • the annotation supports all data types and bulk operations. once you implement the annotation on a class, the class can be referenced from flows, processes, and the custom invocable actions rest api endpoint. // converts a lead as an action in a flow. global class vwfconvertlead implements process.plugin { // this method
runs when called by a flow's legacy apex action. global process.pluginresult invoke( process.pluginrequest request) { // set up variables to store input parameters from // the flow. string leadid = (string) request.inputparameters.get( 'leadid'); string contactid = (string) request.inputparameters.get('contactid'); string accountid = (string) request.inputparameters.get('accountid'); string convertedstatus = (string) request.inputparameters.get('convertedstatus'); boolean overwriteleadsource = (boolean) request.inputparameters.get('overwriteleadsource'); boolean createopportunity = (boolean) request.inputparameters.get('createopportunity'); string opportunityname = (string) request.inputparameters.get('contactid'); boolean sendemailtoowner = (boolean) request.inputparameters.get('sendemailtoowner'); // set the default handling for booleans. if (overwriteleadsource == null) overwriteleadsource = false; if (createopportunity == null) createopportunity = true; if (sendemailtoowner == null) sendemailtoowner = false; // convert the lead by passing it to a helper method. map<string,object> result = new map<string,object>(); result = convertlead(leadid, contactid, accountid, convertedstatus, overwriteleadsource, createopportunity, opportunityname, sendemailtoowner); return new process.pluginresult(result); } 429apex developer guide using salesforce features with apex // this method describes the plug-in and its inputs from // and outputs to the flow. // implementing this method makes the class available // in flow builder as a legacy apex action. global process.plugindescriberesult describe() { // set up plugin metadata process.plugindescriberesult result = new process.plugindescriberesult(); result.description = 'the leadconvert flow plug-in converts a lead into ' + 'an account, a contact, and ' + '(optionally)an opportunity.'; result.tag = 'lead management'; // create a list that stores both mandatory and optional // input parameters from the flow. // note: only primitive types (string, number, etc.) are // supported. collections aren't supported. result.inputparameters = new list<process.plugindescriberesult.inputparameter>{ // lead id (mandatory) new process.plugindescriberesult.inputparameter( 'leadid', process.plugindescriberesult.parametertype.string, true), // account id (optional) new process.plugindescriberesult.inputparameter( 'accountid', process.plugindescriberesult.parametertype.string, false), // contact id (optional) new process.plugindescriberesult.inputparameter( 'contactid', process.plugindescriberesult.parametertype.string, false), // status to use once converted new process.plugindescriberesult.inputparameter( 'convertedstatus', process.plugindescriberesult.parametertype.string, true), new process.plugindescriberesult.inputparameter( 'opportunityname', process.plugindescriberesult.parametertype.string, false), new process.plugindescriberesult.inputparameter( 'overwriteleadsource', process.plugindescriberesult.parametertype.boolean, false), new process.plugindescriberesult.inputparameter( 'createopportunity', process.plugindescriberesult.parametertype.boolean, false), new process.plugindescriberesult.inputparameter( 430apex developer guide using salesforce features with apex 'sendemailtoowner', process.plugindescriberesult.parametertype.boolean, false) }; // create a list that stores output parameters sent // to the flow. result.outputparameters = new list< process.plugindescriberesult.outputparameter>{ // account id of the converted lead new process.plugindescriberesult.outputparameter( 'accountid', process.plugindescriberesult.parametertype.string), // contact id of the converted lead new process.plugindescriberesult.outputparameter( 'contactid', process.plugindescriberesult.parametertype.string), // opportunity id of the converted lead new process.
plugindescriberesult.outputparameter( 'opportunityid', process.plugindescriberesult.parametertype.string) }; return result; } /** * implementation of the leadconvert plug-in. * converts a given lead with several options: * leadid - id of the lead to convert * contactid - * accountid - id of the account to attach the converted * lead/contact/opportunity to. * convertedstatus - * overwriteleadsource - * createopportunity - true if you want to create a new * opportunity upon conversion * opportunityname - name of the new opportunity. * sendemailtoowner - true if you are changing owners upon * conversion and want to notify the new opportunity owner. * * returns: a map with the following output: * accountid - id of the account created or attached * to upon conversion. * contactid - id of the contact created or attached * to upon conversion. * opportunityid - id of the opportunity created * upon conversion. */ public map<string,string> convertlead ( string leadid, string contactid, string accountid, string convertedstatus, 431apex developer guide using salesforce features with apex boolean overwriteleadsource, boolean createopportunity, string opportunityname, boolean sendemailtoowner ) { map<string,string> result = new map<string,string>(); if (leadid == null) throw new convertleadpluginexception( 'lead id cannot be null'); // check for multiple leads with the same id lead[] leads = [select id, firstname, lastname, company from lead where id = :leadid]; if (leads.size() > 0) { lead l = leads[0]; // checkaccount = true, checkcontact = false if (accountid == null && l.company != null) { account[] accounts = [select id, name from account where name = :l.company limit 1]; if (accounts.size() > 0) { accountid = accounts[0].id; } } // perform the lead conversion. database.leadconvert lc = new database.leadconvert(); lc.setleadid(leadid); lc.setoverwriteleadsource(overwriteleadsource); lc.setdonotcreateopportunity(!createopportunity); lc.setconvertedstatus(convertedstatus); if (sendemailtoowner != null) lc.setsendnotificationemail( sendemailtoowner); if (accountid != null && accountid.length() > 0) lc.setaccountid(accountid); if (contactid != null && contactid.length() > 0) lc.setcontactid(contactid); if (createopportunity) { lc.setopportunityname(opportunityname); } database.leadconvertresult lcr = database.convertlead( lc, true); if (lcr.issuccess()) { result.put('accountid', lcr.getaccountid()); result.put('contactid', lcr.getcontactid()); if (createopportunity) { result.put('opportunityid', lcr.getopportunityid()); } } else { string error = lcr.geterrors()[0].getmessage(); throw new convertleadpluginexception(error); } } else { 432apex developer guide using salesforce features with apex throw new convertleadpluginexception( 'no leads found with id : "' + leadid + '"'); } return result; } // utility exception class class convertleadpluginexception extends exception {} } // test class for the lead convert apex plug-in. @istest private class vwfconvertleadtest { static testmethod void basictest() { // create test lead lead testlead = new lead( company='test lead',firstname='john',lastname='doe'); insert testlead; leadstatus convertstatus = [select id, masterlabel from leadstatus where isconverted=true limit 1]; // create test conversion vwfconvertlead aleadplugin = new vwfconvertlead(); map<string,object> inputparams = new map<string,object>(); map<string,object> outputparams = new map<string,object>(); inputparams.put('leadid',testlead.id); input
params.put('convertedstatus', convertstatus.masterlabel); process.pluginrequest request = new process.pluginrequest(inputparams); process.pluginresult result; result = aleadplugin.invoke(request); lead alead = [select name, id, isconverted from lead where id = :testlead.id]; system.assert(alead.isconverted); } /* * this tests lead conversion with * the account id specified. */ static testmethod void basictestwithaccount() { // create test lead lead testlead = new lead( company='test lead',firstname='john',lastname='doe'); insert testlead; 433apex developer guide using salesforce features with apex account testaccount = new account(name='test account'); insert testaccount; // system.debug('account before' + testaccount.id); leadstatus convertstatus = [select id, masterlabel from leadstatus where isconverted=true limit 1]; // create test conversion vwfconvertlead aleadplugin = new vwfconvertlead(); map<string,object> inputparams = new map<string,object>(); map<string,object> outputparams = new map<string,object>(); inputparams.put('leadid',testlead.id); inputparams.put('accountid',testaccount.id); inputparams.put('convertedstatus', convertstatus.masterlabel); process.pluginrequest request = new process.pluginrequest(inputparams); process.pluginresult result; result = aleadplugin.invoke(request); lead alead = [select name, id, isconverted, convertedaccountid from lead where id = :testlead.id]; system.assert(alead.isconverted); //system.debug('account after' + alead.convertedaccountid); system.assertequals(testaccount.id, alead.convertedaccountid); } /* * this tests lead conversion with the account id specified. */ static testmethod void basictestwithaccounts() { // create test lead lead testlead = new lead( company='test lead',firstname='john',lastname='doe'); insert testlead; account testaccount1 = new account(name='test lead'); insert testaccount1; account testaccount2 = new account(name='test lead'); insert testaccount2; // system.debug('account before' + testaccount.id); leadstatus convertstatus = [select id, masterlabel from leadstatus where isconverted=true limit 1]; // create test conversion vwfconvertlead aleadplugin = new vwfconvertlead(); map<string,object> inputparams = new map<string,object>(); 434apex developer guide using salesforce features with apex map<string,object> outputparams = new map<string,object>(); inputparams.put('leadid',testlead.id); inputparams.put('convertedstatus', convertstatus.masterlabel); process.pluginrequest request = new process.pluginrequest(inputparams); process.pluginresult result; result = aleadplugin.invoke(request); lead alead = [select name, id, isconverted, convertedaccountid from lead where id = :testlead.id]; system.assert(alead.isconverted); } /* * -ve test */ static testmethod void errortest() { // create test lead // lead testlead = new lead(company='test lead', // firstname='john',lastname='doe'); leadstatus convertstatus = [select id, masterlabel from leadstatus where isconverted=true limit 1]; // create test conversion vwfconvertlead aleadplugin = new vwfconvertlead(); map<string,object> inputparams = new map<string,object>(); map<string,object> outputparams = new map<string,object>(); inputparams.put('leadid','00q7xxxxxxxxxxx'); inputparams.put('convertedstatus',convertstatus.masterlabel); process.pluginrequest request = new process.pluginrequest(inputparams); process.pluginresult result; try { result = aleadplugin.invoke(request); } catch (exception e) { system.debug('exception' + e); system
.assertequals(1,1); } } /* * this tests the describe() method */ static testmethod void describetest() { 435apex developer guide using salesforce features with apex vwfconvertlead aleadplugin = new vwfconvertlead(); process.plugindescriberesult result = aleadplugin.describe(); system.assertequals( result.inputparameters.size(), 8); system.assertequals( result.outputparameters.size(), 3); } } metadata salesforce uses metadata types and components to represent org configuration and customization. metadata is used for org settings that admins control, or configuration information applied by installed apps and packages. use the classes in the metadata namespace to access metadata from within apex code for tasks that include: • customizing app installs or upgrades—during or after an install (or upgrade), your app can create or update metadata to let users configure your app. • customizing apps after installation—after your app is installed, you can use metadata in apex to let admins configure your app using the ui that your app provides rather than having admins manually use the standard salesforce setup ui. • securely accessing protected metadata—update metadata that your app uses internally without exposing these types and components to your users. • creating custom configuration tools—use metadata in apex to provide custom tools for admins to customize apps and packages. metadata access in apex is available for apex classes using api version 40.0 and later. for more information on metadata types and components, see the metadata api developer guide and the custom metadata types implementation guide. in this section: retrieving and deploying metadata retrieve and deploy metadata using the metadata.operations class. supported metadata types apex supports a subset of metadata types and components. security considerations be aware of security considerations when accessing metadata using apex. testing metadata deployments apex code that accesses metadata must be properly tested. see also: apex reference guide: metadata namespace 436apex developer guide using salesforce features with apex retrieving and deploying metadata retrieve and deploy metadata using the metadata.operations class. use the metadata.operations.retrieve() method to synchronously retrieve metadata from the current org. provide a list of metadata component names that you want to retrieve. salesforce returns a list of matching component data, represented by component classes that derive from metadata.metadata. use the metadata.operations.enqueuedeployment() method to asynchronously deploy metadata to the current org. deployment is queued for asynchronous processing. when deploying metadata, you can create and update components, but not delete components. there are limitations on which components that apps and packages can deploy and which types of apps and packages can deploy to which types of orgs. for more information see security considerations. use the full name of the metadata component when retrieving and deploying metadata. the full name may include the namespace, metadata type, and component name. if you’re updating components in a namespace, you also need to qualify the namespace for the component in the full name. for example, the full name for a custom metadata "mdtype1__mdt" component named "component1" that is contained in the "mypackage" namespace is "mypackage__mdtype1__mdt.mypackage__component1". for more information on the metadata component full name syntax, see metadata base type in the metadata api developer guide. you can retrieve and deploy metadata in post install scripts. in uninstall scripts, you can only retrieve, not deploy, metadata from apex code. see metadata.operations for code examples for retrieving and deploying metadata. supported metadata types apex supports a subset of metadata types and components. metadata access in apex is limited to types and components that support the use cases described in metadata. apps and packages can use the metadata feature in apex to retrieve and deploy the following metadata types and components: • records of custom metadata types • layouts security considerations be aware of security considerations when accessing metadata using apex. generally, apex classes installed in the subscriber org can access any public, supported metadata type or component in the subscriber org. protected metadata, such as a custom metadata type that’s been marked protected, can only be accessed by apex classes in the same namespace as the protected metadata. additionally, for managed packages, if the managed package isn’t approved by salesforce via security review, apex classes in the package can’t access metadata (public or protected) unless the deploy metadata from non-certified package
versions via apex org preference is enabled. this preference, located under setup > apex settings, must be enabled if admins or developers are installing managed packages that haven’t passed security review for app testing or pilot purposes. for deployments, because metadata.operations.enqueuedeployment() uses asynchronous apex, queued deployment jobs and deployment callbacks are counted as asynchronous jobs in the current org. queued deployment jobs and callbacks are subject to governor limits. see lightning platform apex limits. apps that access metadata via apex must notify users that the app can retrieve or deploy metadata in the subscriber org. for installs that access metadata, notify users in the description of your package. you can write your own notice, or use this sample: this package can access and change metadata outside its namespace in the salesforce org where it’s installed. salesforce verifies the notice during the security review. for more information, see the isvforce guide. 437apex developer guide using salesforce features with apex testing metadata deployments apex code that accesses metadata must be properly tested. to provide apex test coverage for metadata deployments, write tests that verify both the set up of the deployment request and handling of the deployment results. tests for deployment request code verify the metadata components and component values that get created and assert that the deploycontainer contains exactly what needs to be deployed. tests for deployment result code verify that your deploycallback handles expected and unexpected results. your deploycallback is normally called by salesforce as part of the asynchronous deployment process. therefore, to test your callback outside of the deployment process, create tests that use your callback class directly. you also must create test deployresults and deploycallbackcontext instances to test your deploycallback.handleresults() method. when creating a test instance of deploycallbackcontext, subclass deploycallbackcontext and provide your own implementation of getcallbackjobid(). // deploycallbackcontext subclass for testing that returns myjobid public class testingdeploycallbackcontext extends metadata.deploycallbackcontext { private myjobid = null; // define to a canned id you can use for testing public override id getcallbackjobid() { return myjobid; } } permission set groups to provide apex test coverage for permission set groups, write tests using the calculatepermissionsetgroup() method in the system.test class. the calculatepermissionsetgroup() method forces an immediate calculation of aggregate permissions for a specified permission set group. as the forced calculation counts against apex cpu limits, and can require complex data setup, it’s a best practice to minimize the number of times you perform this operation. set this test to run once in a test setup method, then reuse the data in subsequent tests. @istest public class psgtest { @istest static void testpsg() { // get the psg by name (may have been modified in deployment) permissionsetgroup psg = [select id, status from permissionsetgroup where developername='mypsg']; // force calculation of the psg if it is not already updated if (psg.status != 'updated') { test.calculatepermissionsetgroup(psg.id); } // assign psg to current user (this fails if psg is outdated) insert new permissionsetassignment(permissionsetgroupid = psg.id, assigneeid = userinfo.getuserid()); // additional tests to validate permissions granted by psg 438apex developer guide using salesforce features with apex } } see also: salesforce help: permission set groups apex reference guide: test class platform cache the lightning platform cache layer provides faster performance and better reliability when caching salesforce session and org data. specify what to cache and for how long without using custom objects and settings or overloading a visualforce view state. platform cache improves performance by distributing cache space so that some applications or operations don’t steal capacity from others. because apex runs in a multi-tenant environment with cached data living alongside internally cached data, caching involves minimal disruption to core salesforce processes. in this section: platform cache features the platform cache api lets you store and retrieve data that’s tied to salesforce sessions or shared across your org. put, retrieve, or remove cache values by using the session, org, sessionpartition, and orgpartition classes in the cache namespace. use the platform cache partition tool in setup to create or remove org partitions and allocate their cache capacities to balance performance across apps. platform cache considerations review these considerations when working with platform cache. platform cache limits the following limits
apply when using platform cache. platform cache partitions use platform cache partitions to improve the performance of your applications. partitions allow you to distribute cache space in the way that works best for your applications. caching data to designated partitions ensures that it’s not overwritten by other applications or less-critical data. platform cache internals platform cache uses local cache and a least recently used (lru) algorithm to improve performance. store and retrieve values from the session cache use the cache.session and cache.sessionpartition classes to manage values in the session cache. to manage values in any partition, use the methods in the cache.session class. if you’re managing cache values in one partition, use the cache.sessionpartition methods instead. store and retrieve values from the org cache use the cache.org and cache.orgpartition classes to manage values in the org cache. to manage values in any partition, use the methods in the cache.org class. if you’re managing cache values in one partition, use the cache.orgpartition methods instead. use a visualforce global variable for the platform cache you can access cached values stored in the session or org cache from a visualforce page with global variables. 439apex developer guide using salesforce features with apex safely cache values with the cachebuilder interface a platform cache best practice is to ensure that your apex code handles cache misses by testing for cache requests that return null. you can write this code yourself. or, you can use the cache.cachebuilder interface, which makes it easy to safely store and retrieve values to a session or org cache. platform cache best practices platform cache can greatly improve performance in your applications. however, it’s important to follow these guidelines to get the best cache performance. in general, it’s more efficient to cache a few large items than to cache many small items separately. also be mindful of cache limits to prevent unexpected cache evictions. platform cache features the platform cache api lets you store and retrieve data that’s tied to salesforce sessions or shared across your org. put, retrieve, or remove cache values by using the session, org, sessionpartition, and orgpartition classes in the cache namespace. use the platform cache partition tool in setup to create or remove org partitions and allocate their cache capacities to balance performance across apps. there are two types of cache: • session cache—stores data for individual user sessions. for example, in an app that finds customers within specified territories, the calculations that run while users browse different locations on a map are reused. session cache lives alongside a user session. the maximum life of a session is eight hours. session cache expires when its specified time-to-live (ttlsecs value) is reached or when the session expires after eight hours, whichever comes first. • org cache—stores data that any user in an org reuses. for example, the contents of navigation bars that dynamically display menu items based on user profile are reused. unlike session cache, org cache is accessible across sessions, requests, and org users and profiles. org cache expires when its specified time-to-live (ttlsecs value) is reached. additionally, salesforce provides 3 mb of free platform cache capacity for appexchange-certified and security-reviewed managed packages through a capacity type called provider free capacity. you can allocate capacities to session cache and org cache from the provider free capacity. the best data to cache is: • reused throughout a session • static (not rapidly changing) • otherwise expensive to retrieve for both session and org caches, you can construct calls so that cached data in one namespace isn’t overwritten by similar data in another. optionally use the cache.visibility enumeration to specify whether apex code can access cached data in a namespace outside of the invoking namespace. each cache operation depends on the apex transaction within which it runs. if the entire transaction fails, all cache operations in that transaction are rolled back. try platform cache to test performance improvements by using platform cache in your own org, you can request trial cache for your production org. enterprise, unlimited, and performance editions come with some cache, but adding more cache often provides greater performance. when your trial request is approved, you can allocate capacity to partitions and experiment with using the cache for different scenarios. testing the cache on a trial basis lets you make an informed decision about whether to purchase cache. for more information about trial cache, see “request a platform cache trial” in salesforce help. 440apex developer guide using salesforce features with apex you can request additional cache space to improve the performance of your
application. for more information about requesting additional cache, see "request additional platform cache" in salesforce help. for more information about provider free capacity cache, see “set up a platform cache partition using provider free capacity” in salesforce help. note: platform cache isn’t supported in professional edition. see also: apex reference guide: session class apex reference guide: org class apex reference guide: partition class apex reference guide: orgpartition class apex reference guide: sessionpartition class apex reference guide: cachebuilder interface platform cache considerations review these considerations when working with platform cache. • cache isn’t persisted. there’s no guarantee against data loss. • some or all cache is invalidated when you modify an apex class in your org. • data in the cache isn’t encrypted. • org cache supports concurrent reads and writes across multiple simultaneous apex transactions. for example, a transaction updates the key petname with the value fido. at the same time, another transaction updates the same key with the value felix. both writes succeed, but one of the two values is chosen arbitrarily as the winner, and later transactions read that one value. however, this arbitrary choice is per key rather than per transaction. for example, suppose one transaction writes pettype="cat" and petname="felix". then, at the same moment, another transaction writes pettype="dog" and petname="fido". in this case, the pettype winning value could be from the first transaction, and the petname winning value could be from the second transaction. subsequent get() calls on those keys would return pettype="cat" and petname="fido". • cache misses can happen. we recommend constructing your code to consider a case where previously cached items aren’t found. alternatively, use the cachebuilder interface, which checks for cache misses. • all platform cache statistical methods: getavggetsize(), getavggettime(), getmaxgetsize(), getmaxgettime(), and getmissrate()report data starting from the time the cache server was restarted, and do not include data prior to the restart. • partitions must adhere to the limits within salesforce. • the session cache can store values up to eight hours. the org cache can store values up to 48 hours. • for orgs that use salesforce flow: – when a process contains a scheduled action, make sure that later actions in the process don't invoke apex code that stores or retrieves values from the session cache. the session-cache restriction applies to apex actions and to changes that the process makes to the database that cause apex triggers to fire. – when a flow contains a pause element, make sure that later elements in the flow don't invoke apex code that stores or retrieves values from the session cache. the session-cache restriction applies to apex actions and to changes that the flow makes to the database that cause apex triggers to fire. 441apex developer guide using salesforce features with apex platform cache limits the following limits apply when using platform cache. edition-specific limits the following table shows the amount of platform cache available for different types of orgs. to purchase more cache, contact your salesforce representative. edition cache size enterprise 10 mb unlimited and performance 30 mb all others 0 mb partition size limits limit value minimum partition size 1 mb session cache limits limit value maximum size of a single cached item (for put() methods) 100 kb maximum local cache size for a partition, per-request1 500 kb minimum developer-assigned time-to-live 300 seconds (5 minutes) maximum developer-assigned time-to-live 28,800 seconds (8 hours) maximum session cache time-to-live 28,800 seconds (8 hours) org cache limits limit value maximum size of a single cached item (for put() methods) 100 kb maximum local cache size for a partition, per-request1 1,000 kb minimum developer-assigned time-to-live 300 seconds (5 minutes) maximum developer-assigned time-to-live 172,800 seconds (48 hours) default org cache time-to-live 86,400 seconds (24 hours) 1 local cache is the application server’s in-memory container that the client interacts with during a request. 442apex developer guide using salesforce features with apex platform cache partitions use platform cache partitions to improve the performance of your applications. partitions allow you to distribute cache space in the way that works best for your applications. caching data to designated partitions ensures that it’s not overwritten by other
applications or less-critical data. to use platform cache, first set up partitions using the platform cache partition tool in setup. once you’ve set up partitions, you can add, access, and remove data from them using the platform cache apex api. to access the partition tool in setup, enter platform cache in the quick find box, then select platform cache. use the partition tool to: • setup a platform cache partition with provider free capacity. • request trial cache. • create, edit, or delete cache partitions. • allocate the session cache and org cache capacities of each partition to balance performance across apps. • view a snapshot of the org’s current cache capacity, breakdown, and partition allocations (in kb or mb). • view details about each partition. • make any partition the default partition. to use platform cache, create at least one partition. each partition has one session cache and one org cache segment and you can allocate separate capacity to each segment. session cache can be used to store data for individual user sessions, and org cache is for data that any users in an org can access. you can distribute your org’s cache space across any number of partitions. session and org cache allocations can be zero, or five or greater, and they must be whole numbers. the sum of all partition allocations, including the default partition, equals the platform cache total allocation. the total allocated capacity of all cache segments must be less than or equal to the org’s overall capacity. you can define any partition as the default partition, but you can have only one default partition. when a partition has no allocation, cache operations (such as get and put) are not invoked, and no error is returned. when performing cache operations within the default partition, you can omit the partition name from the key. after you set up partitions, you can use apex code to perform cache operations on a partition. for example, use the cache.sessionpartition and cache.orgpartition classes to put, retrieve, or remove values on a specific partition’s cache. use cache.session and cache.org to get a partition or perform cache operations by using a fully qualified key. packaging platform cache partitions when packaging an application that uses platform cache, add any referenced partitions to your packages explicitly. partitions aren’t pulled into packages automatically, as other dependencies are. partition validation occurs during run time, rather than compile time. therefore, if a partition is missing from a package, you don’t receive an error message at compile time. note: if platform cache code is intended for a package, don’t use the default partition in the package. instead, explicitly reference and package a non-default partition. any package containing the default partition can’t be deployed. see also: apex reference guide: partition class apex reference guide: orgpartition class apex reference guide: sessionpartition class metadata api developer’s guide: platform cache partition type 443apex developer guide using salesforce features with apex platform cache internals platform cache uses local cache and a least recently used (lru) algorithm to improve performance. local cache platform cache uses local cache to improve performance, ensure efficient use of the network, and support atomic transactions. local cache is the application server’s in-memory container that the client interacts with during a request. cache operations don’t interact with the caching layer directly, but instead interact with local cache. for session cache, all cached items are loaded into local cache upon first request. all subsequent interactions use the local cache. similarly, an org cache get operation retrieves a value from the caching layer and stores it in the local cache. subsequent requests for this value are retrieved from the local cache. all mutable operations, such as put and remove, are also performed against the local cache. upon successful completion of the request, mutable operations are committed. note: local cache doesn’t support concurrent operations. mutable operations, such as put and remove, are performed against the local cache and are only committed when the entire apex request is successful. therefore, other simultaneous requests don’t see the results of the mutable operations. atomic transactions each cache operation depends on the apex request that it runs in. if the entire request fails, all cache operations in that request are rolled back. behind the scenes, the use of local cache supports these atomic transactions. eviction algorithm when possible, platform cache uses an lru algorithm to evict keys from the cache. when cache limits are reached, keys are evicted until the cache is reduced to 100-percent capacity. if session cache is used, the system removes cache evenly
from all existing session cache instances. local cache also uses an lru algorithm. when the maximum local cache size for a partition is reached, the least recently used items are evicted from the local cache. see also: platform cache limits store and retrieve values from the session cache use the cache.session and cache.sessionpartition classes to manage values in the session cache. to manage values in any partition, use the methods in the cache.session class. if you’re managing cache values in one partition, use the cache.sessionpartition methods instead. cache.session methods to store a value in the session cache, call the cache.session.put() method and supply a key and value. the key name is in the format namespace.partition.key. for example, for namespace ns1, partition partition1, and key orderdate, the fully qualified key name is ns1.partition1.orderdate. this example stores a datetime cache value with the key orderdate. next, the snippet checks if the orderdate key is in the cache, and if so, retrieves the value from the cache. // add a value to the cache datetime dt = datetime.parse('06/16/2015 11:46 am'); cache.session.put('ns1.partition1.orderdate', dt); 444apex developer guide using salesforce features with apex if (cache.session.contains('ns1.partition1.orderdate')) { datetime cacheddt = (datetime)cache.session.get('ns1.partition1.orderdate'); } to refer to the default partition and the namespace of the invoking class, omit the namespace.partition prefix and specify the key name. cache.session.put('orderdate', dt); if (cache.session.contains('orderdate')) { datetime cacheddt = (datetime)cache.session.get('orderdate'); } the local prefix refers to the namespace of the current org where the code is running, regardless of whether the org has a namespace defined. if the org has a namespace defined as ns1, the following two statements are equivalent. cache.session.put('local.mypartition.orderdate', dt); cache.session.put('ns1.mypartition.orderdate', dt); note: the local prefix in an installed managed package refers to the namespace of the subscriber org and not the package’s namespace. the cache put calls are not allowed in a partition that the invoking class doesn’t own. the put() method has multiple versions (or overloads), and each version takes different parameters. for example, to specify that your cached value can’t be overwritten by another namespace, set the last parameter of this method to true. the following example also sets the lifetime of the cached value (3600 seconds or 1 hour) and makes the value available to any namespace. // add a value to the cache with options cache.session.put('ns1.partition1.totalsum', '500', 3600, cache.visibility.all, true); to retrieve a cached value from the session cache, call the cache.session.get() method. because cache.session.get() returns an object, we recommend that you cast the returned value to a specific type. // get a cached value object obj = cache.session.get('ns1.partition1.orderdate'); // cast return value to a specific data type datetime dt2 = (datetime)obj; cache.sessionpartition methods if you’re managing cache values in one partition, use the cache.sessionpartition methods instead. after the partition object is obtained, the process of adding and retrieving cache values is similar to using the cache.session methods. the cache.sessionpartition methods are easier to use because you specify only the key name without the namespace and partition prefix. first, get the session partition and specify the desired partition. the partition name includes the namespace prefix: namespace.partition. you can manage the cached values in that partition by adding and retrieving cache values on the obtained partition object. the following example obtains the partition named mypartition in the myns namespace. next, if the cache contains a value with the key booktitle, this cache value is retrieved. a new value is added with key orderdate and today’s date. // get partition cache.sessionpartition sessionpart = cache.session.getpartition('myns.mypartition'); // retrieve cache value from the partition if (sessionpart
.contains('booktitle')) { string cachedtitle = (string)sessionpart.get('booktitle'); } 445apex developer guide using salesforce features with apex // add cache value to the partition sessionpart.put('orderdate', date.today()); this example calls the get method on a partition in one expression without assigning the partition instance to a variable. // or use dot notation to call partition methods string cachedauthor = (string)cache.session.getpartition('myns.mypartition').get('bookauthor'); see also: apex reference guide: session class apex reference guide: sessionpartition class store and retrieve values from the org cache use the cache.org and cache.orgpartition classes to manage values in the org cache. to manage values in any partition, use the methods in the cache.org class. if you’re managing cache values in one partition, use the cache.orgpartition methods instead. cache.org methods to store a value in the org cache, call the cache.org.put() method and supply a key and value. the key name is in the format namespace.partition.key. for example, for namespace ns1, partition partition1, and key orderdate, the fully qualified key name is ns1.partition1.orderdate. this example stores a datetime cache value with the key orderdate. next, the snippet checks if the orderdate key is in the cache, and if so, retrieves the value from the cache. // add a value to the cache datetime dt = datetime.parse('06/16/2015 11:46 am'); cache.org.put('ns1.partition1.orderdate', dt); if (cache.org.contains('ns1.partition1.orderdate')) { datetime cacheddt = (datetime)cache.org.get('ns1.partition1.orderdate'); } to refer to the default partition and the namespace of the invoking class, omit the namespace.partition prefix and specify the key name. cache.org.put('orderdate', dt); if (cache.org.contains('orderdate')) { datetime cacheddt = (datetime)cache.org.get('orderdate'); } the local prefix refers to the namespace of the current org where the code is running. the local prefix refers to the namespace of the current org where the code is running, regardless of whether the org has a namespace defined. if the org has a namespace defined as ns1, the following two statements are equivalent. cache.org.put('local.mypartition.orderdate', dt); cache.org.put('ns1.mypartition.orderdate', dt); note: the local prefix in an installed managed package refers to the namespace of the subscriber org and not the package’s namespace. the cache put calls are not allowed in a partition that the invoking class doesn’t own. 446
apex developer guide using salesforce features with apex the put() method has multiple versions (or overloads), and each version takes different parameters. for example, to specify that your cached value can’t be overwritten by another namespace, set the last parameter of this method to true. the following example also sets the lifetime of the cached value (3600 seconds or 1 hour) and makes the value available to any namespace. // add a value to the cache with options cache.org.put('ns1.partition1.totalsum', '500', 3600, cache.visibility.all, true); to retrieve a cached value from the org cache, call the cache.org.get() method. because cache.org.get() returns an object, we recommend that you cast the returned value to a specific type. // get a cached value object obj = cache.org.get('ns1.partition1.orderdate'); // cast return value to a specific data type datetime dt2 = (datetime)obj; cache.orgpartition methods if you’re managing cache values in one partition, use the cache.orgpartition methods instead. after the partition object is obtained, the process of adding and retrieving cache values is similar to using the cache.org methods. the cache.orgpartition methods are easier to use because you specify only the key name without the namespace and partition prefix. first, get the org partition and specify the desired partition. the partition name includes the namespace prefix: namespace.partition. you can manage the cached values in that partition by adding and retrieving cache values on the obtained partition object. the following example obtains the partition named mypartition in the myns namespace. if the cache contains a value with the key booktitle, this cache value is retrieved. a new value is added with key orderdate and today’s date. // get partition cache.orgpartition orgpart = cache.org.getpartition('myns.mypartition'); // retrieve cache value from the partition if (orgpart.contains('booktitle')) { string cachedtitle = (string)orgpart.get('booktitle'); } // add cache value to the partition orgpart.put('orderdate', date.today()); this example calls the get method on a partition in one expression without assigning the partition instance to a variable. // or use dot notation to call partition methods string cachedauthor = (string)cache.org.getpartition('myns.mypartition').get('bookauthor'); see also: apex reference guide: org class apex reference guide: orgpartition class use a visualforce global variable for the platform cache you can access cached values stored in the session or org cache from a visualforce page with global variables. you can use either the $cache.session or $cache.org global variable. include the global variable’s fully qualified key name with the namespace and partition name. 447apex developer guide using salesforce features with apex this output text component retrieves a session cache value using the global variable’s namespace, partition, and key. <apex:outputtext value="{!$cache.session.mynamespace.mypartition.key1}"/> this example is similar but uses the $cache.org global variable to retrieve a value from the org cache. <apex:outputtext value="{!$cache.org.mynamespace.mypartition.key1}"/> note: the remaining examples show how to access the session cache using the $cache.session global variable. the equivalent org cache examples are the same except that you use the $cache.org global variable instead. unlike with apex methods, you can’t omit the mynamespace.mypartition prefix to reference the default partition in the org. if a namespace isn’t defined for the org, use local to refer to the org’s namespace. <apex:outputtext value="{!$cache.session.local.mypartition.key1}"/> the cached value is sometimes a data structure that has properties or methods, like an apex list or a custom class. in this case, you can access the properties in the $cache.session or $cache.org expression by using dot notation. for example, this markup invokes the list.size() apex method if the value of numberslist is declared as a list. <apex:outputtext value="{!$cache.session.local.mypartition.numberslist.size}"/> this example accesses the value property on the mydata cache value that
is declared as a custom class. <apex:outputtext value="{!$cache.session.local.mypartition.mydata.value}"/> if you’re using cachebuilder, qualify the key name with the class that implements the cachebuilder interface and the literal string _b_, in addition to the namespace and partition name. in this example, the class that implements cachebuilder is called cachebuilderimpl. <apex:outputtext value="{!$cache.session.mynamespace.mypartition.cachebuilderimpl_b_key1}"/> safely cache values with the cachebuilder interface a platform cache best practice is to ensure that your apex code handles cache misses by testing for cache requests that return null. you can write this code yourself. or, you can use the cache.cachebuilder interface, which makes it easy to safely store and retrieve values to a session or org cache. rather than just declaring what you want to cache in your apex class, create an inner class that implements the cachebuilder interface. the interface has a single method, doload(string var), which you override by coding the logic that builds the cached value based on the doload(string var) method’s argument. to retrieve a value that you’ve cached with cachebuilder, you don’t call the doload(string var) method directly. instead, it’s called indirectly by salesforce the first time you reference the class that implements cachebuilder. subsequent calls get the value from the cache, as long as the value exists. if the value doesn’t exist, the doload(string var) method is called again to build the value and then return it. as a result, you don’t execute put() methods when using the cachebuilder interface. and because the doload(string var) method checks for cache misses, you don’t have to write the code to check for nulls yourself. let’s look at an example. suppose you’re coding an apex controller class for a visualforce page. in the apex class, you often run a soql query that looks up a user record based on a user id. soql queries can be expensive, and salesforce user records don’t typically change much, so the user information is a good candidate for cachebuilder. in your controller class, create an inner class that implements the cachebuilder interface and overrides the doload(string var) method. then add the soql code to the doload(string var) method with the user id as its parameter. class userinfocache implements cache.cachebuilder { public object doload(string userid) { 448apex developer guide using salesforce features with apex user u = (user)[select id, isactive, username from user where id =: userid]; return u; } } to retrieve the user record from the org cache, execute the org.get(cachebuilder, key) method, passing it the userinfocache class and the user id. similarly, use session.get(cachebuilder, key) and partition.get(cachebuilder, key) to retrieve the value from the session or partition cache, respectively. user batman = (user) cache.org.get(userinfocache.class, ‘00541000000ek4c'); when you run the get() method, salesforce searches the cache using a unique key that consists of the strings 00541000000ek4c and userinfocache. if salesforce finds a cached value, it returns it. for this example, the cached value is a user record associated with the id 00541000000ek4c. if salesforce doesn’t find a value, it executes the doload(string var) method of userinfocache again (and reruns the soql query), caches the user record, and then returns it. cachebuilder coding requirements follow these requirements when you code a class that implements the cachebuilder interface. • the doload(string var) method must take a string parameter, even if you do not use the parameter in the method’s code. salesforce uses the string, along with the class name, to build a unique key for the cached value. • the doload(string var) method can return any value, including null. if a null value is returned, it is delivered directly to the cachebuilder consumer and not cached. cachebuilder consumers are expected to handle null values gracefully. we recommend using null values to reflect a temporary failure to re-build the cache key. • the class that implements cachebuilder must be non-static because salesforce instantiates a new instance of the class and runs the doload(
string var) method to create the cached value. see also: apex reference guide: cachebuilder interface platform cache best practices platform cache can greatly improve performance in your applications. however, it’s important to follow these guidelines to get the best cache performance. in general, it’s more efficient to cache a few large items than to cache many small items separately. also be mindful of cache limits to prevent unexpected cache evictions. evaluate the performance impact to test whether platform cache improves performance in your application, calculate the elapsed time with and without using the cache. don’t rely on the apex debug log timestamp for the execution time. use the system.currenttimemillis() method instead. for example, first call system.currenttimemillis() to get the start time. perform application logic, fetching the data from either the cache or another data source. then calculate the elapsed time. long starttime = system.currenttimemillis(); // your code here long elapsedtime = system.currenttimemillis() - starttime; system.debug(elapsedtime); 449apex developer guide using salesforce features with apex handle cache misses gracefully ensure that your code handles cache misses by testing cache requests that return null. to help with debugging, add logging information for cache operations. alternatively, use the cache.cachebuilder interface, which checks for cache misses. public class cachemanager { private boolean cacheenabled; public void cachemanager() { cacheenabled = true; } public boolean toggleenabled() { // use for testing misses cacheenabled = !cacheenabled; return cacheenabled; } public object get(string key) { if (!cacheenabled) return null; object value = cache.session.get(key); if (value != null) system.debug(logginglevel.debug, 'hit for key ' + key); return value; } public void put(string key, object value, integer ttl) { if (!cacheenabled) return; cache.session.put(key, value, ttl); // for redundancy, save to db system.debug(logginglevel.debug, 'put() for key ' + key); } public boolean remove(string key) { if (!cacheenabled) return false; boolean removed = cache.session.remove(key); if (removed) { system.debug(logginglevel.debug, 'removed key ' + key); return true; } else return false; } } group cache requests when possible, group cache requests, but be aware of caching limits. to help improve performance, perform cache operations on a list of keys rather than on individual keys. for example, if you know which keys are necessary to invoke a visualforce page or perform a task in apex, retrieve all keys at once. to retrieve multiple keys, call get(keys) in an initialization method. cache larger items it’s more efficient to cache a few large items than to cache many small items separately. caching many small items decreases performance and increases overhead, including total serialization size, serialization time, cache commit time, and cache capacity usage. 450apex developer guide using salesforce features with apex don’t add many small items to the platform cache within one request. instead, wrap data in larger items, such as lists. if a list is large, consider breaking it into multiple items. here’s an example of what to avoid. // don't do this! public class mycontroller { public void initcache() { list<account> accts = [select id, name, phone, industry, description from account limit 1000]; for (integer i=0; i<accts.size(); i++) { cache.org.put('acct' + i, accts.get(i)); } } } instead, wrap the data in a few reasonably large items without exceeding the limit on the size of single cached items. // do this instead. public class mycontroller { public void initcache() { list<account> accts = [select id, name, phone, industry, description from account limit 1000]; cache.org.put('accts', accts); } } another good example of caching larger items is to encapsulate data in an apex class. for example, you can create a class that wraps session data, and cache an instance of the class rather than the individual data items. caching the class instance improves overall serialization size and performance. be aware of cache limits when you add items to the cache, be aware of
the following limits. cache partition size limit when the cache partition limit is reached, keys are evicted until the cache is reduced to 100% capacity. platform cache uses a least recently used (lru) algorithm to evict keys from the cache. local cache size limit when you add items to the cache, make sure that you are not exceeding local cache limits within a request. the local cache limit for the session cache is 500 kb and 1,000 kb for the org cache. if you exceed the local cache limit, items can be evicted from the local cache before the request has been committed. this eviction can cause unexpected misses and long serialization time and can waste resources. single cached item size limit the size of individual cached items is limited to 100 kb. if the serialized size of an item exceeds this limit, the cache.itemsizelimitexceededexception exception is thrown. it’s a good practice to catch this exception and reduce the size of the cached item. use the cache diagnostics page (sparingly) to determine how much of the cache is used, check the platform cache diagnostics page. to reach the diagnostics page: 451apex developer guide using salesforce features with apex 1. make sure that cache diagnostics is enabled for the user (on the user detail page). 2. on the platform cache partition page, click the partition name. 3. click the link to the diagnostics page for the partition. the diagnostics page provides valuable information, including the capacity usage, keys, and serialized and compressed sizes of the cached items. the session cache and org cache have separate diagnostics pages. the session cache diagnostics are per session, and they don’t provide insight across all active sessions. note: generating the diagnostics page gathers all partition-related information and is an expensive operation. use it sparingly. minimize expensive operations consider the following guidelines to minimize expensive operations. • use cache.org.getkeys() and cache.org.getcapacity() sparingly. both methods are expensive, because they traverse all partition-related information looking for or making calculations for a given partition. note: cache.session usage is not expensive. • avoid calling the contains(key) method followed by the get(key) method. if you intend to use the key value, simply call the get(key) method and make sure that the value is not equal to null. • clear the cache only when necessary. clearing the cache traverses all partition-related cache space, which is expensive. after clearing the cache, your application will likely regenerate the cache by invoking database queries and computations. this regeneration can be complex and extensive and impact your application’s performance. see also: platform cache limits apex reference guide: cachebuilder interface salesforce knowledge salesforce knowledge is a knowledge base where users can easily create and manage content, known as articles, and quickly find and view the articles they need. use apex to access these salesforce knowledge features: in this section: knowledge management users can write, publish, archive, and manage articles using apex in addition to the salesforce user interface. promoted search terms promoted search terms are useful for promoting a salesforce knowledge article that you know is commonly used to resolve a support issue when an end user’s search contains certain keywords.users can promote an article in search results by associating keywords with the article in apex (by using the searchpromotionrule sobject) in addition to the salesforce user interface. suggest salesforce knowledge articles provide users with shortcuts to navigate to relevant articles before they perform a search. call search.suggest(searchtext, objecttype, options) to return a list of salesforce knowledge articles whose titles match a user’s search query string. 452apex developer guide using salesforce features with apex knowledge management users can write, publish, archive, and manage articles using apex in addition to the salesforce user interface. use the methods in the kbmanagement.publishingservice class to manage the following parts of the lifecycle of an article and its translations: • publishing • updating • retrieving • deleting • submitting for translation • setting a translation to complete or incomplete status • archiving • assigning review tasks for draft articles or translations note: date values are based on gmt. to use the methods in this class, you must enable salesforce knowledge. see salesforce knowledge implementation guide for more information on setting up salesforce knowledge. see also: apex reference guide: publishingservice class promoted search terms promoted search terms are useful for promoting a salesforce knowledge article that you know
is commonly used to resolve a support issue when an end user’s search contains certain keywords.users can promote an article in search results by associating keywords with the article in apex (by using the searchpromotionrule sobject) in addition to the salesforce user interface. articles must be in published status (with a publishsatus field value of online) for you to manage their promoted terms. example: this code sample shows how to add a search promotion rule. this sample performs a query to get published articles of type myarticle__kav. next, the sample creates a searchpromotionrule sobject to promote articles that contain the word “salesforce” and assigns the first returned article to it. finally, the sample inserts this new sobject. // identify the article to promote in search results list<myarticle__kav> articles = [select id from myarticle__kav where publishstatus='online' and language='en_us' and id='article id']; // define the promotion rule searchpromotionrule s = new searchpromotionrule( query='salesforce', promotedentity=articles[0]); // save the new rule insert s; to perform dml operations on the searchpromotionrule sobject, you must enable salesforce knowledge. 453apex developer guide using salesforce features with apex suggest salesforce knowledge articles provide users with shortcuts to navigate to relevant articles before they perform a search. call search.suggest(searchtext, objecttype, options) to return a list of salesforce knowledge articles whose titles match a user’s search query string. to return suggestions, enable salesforce knowledge. see salesforce knowledge implementation guide for more information on setting up salesforce knowledge. this visualforce page has an input field for searching articles or accounts. when the user presses the suggest button, suggested records are displayed. if there are more than five results, the more results button appears. to display more results, click the button. <apex:page controller="suggestiondemocontroller"> <apex:form > <apex:pageblock mode="edit" id="block"> <h1>article and record suggestions</h1> <apex:pageblocksection > <apex:pageblocksectionitem > <apex:outputpanel > <apex:panelgroup > <apex:selectlist value="{!objecttype}" size="1"> <apex:selectoption itemlabel="account" itemvalue="account" /> <apex:selectoption itemlabel="article" itemvalue="knowledgearticleversion" /> <apex:actionsupport event="onchange" rerender="block"/> </apex:selectlist> </apex:panelgroup> <apex:panelgroup > <apex:inputhidden id="nbresult" value="{!nbresult}" /> <apex:outputlabel for="searchtext">search text</apex:outputlabel> &nbsp; <apex:inputtext id="searchtext" value="{!searchtext}"/> <apex:commandbutton id="suggestbutton" value="suggest" action="{!dosuggest}" rerender="block"/> <apex:commandbutton id="suggestmorebutton" value="more results..." action="{!dosuggestmore}" rerender="block" style="{!if(hasmoreresults, '', 'display: none;')}"/> </apex:panelgroup> </apex:outputpanel> </apex:pageblocksectionitem> </apex:pageblocksection> <apex:pageblocksection title="results" id="results" columns="1" rendered="{!results.size>0}"> <apex:datalist value="{!results}" var="w" type="1"> id: {!w.sobject['id']} <br /> <apex:panelgroup rendered="{!objecttype=='knowledgearticleversion'}"> title: {!w.sobject['title']} </apex:panelgroup> <apex:panelgroup rendered="{!objecttype!='knowledgearticleversion'}"> name: {!w.sobject['name']} 454apex developer guide using salesforce features with apex </apex:panelgroup> <hr /> </apex:datalist> </apex:pageblocksection> <apex:pageblocksection id="noresults" rendered="{!results.size==0}"> no results </
apex:pageblocksection> <apex:pageblocksection rendered="{!len(searchtext)>0}"> search text: {!searchtext} </apex:pageblocksection> </apex:pageblock> </apex:form> </apex:page> this code is the custom visualforce controller for the page: public class suggestiondemocontroller { public string searchtext; public string language = 'en_us'; public string objecttype = 'account'; public integer nbresult = 5; public transient search.suggestionresults suggestionresults; public string getsearchtext() { return searchtext; } public void setsearchtext(string s) { searchtext = s; } public integer getnbresult() { return nbresult; } public void setnbresult(integer n) { nbresult = n; } public string getlanguage() { return language; } public void setlanguage(string language) { this.language = language; } public string getobjecttype() { return objecttype; } public void setobjecttype(string objecttype) { this.objecttype = objecttype; } 455apex developer guide using salesforce features with apex public list<search.suggestionresult> getresults() { if (suggestionresults == null) { return new list<search.suggestionresult>(); } return suggestionresults.getsuggestionresults(); } public boolean gethasmoreresults() { if (suggestionresults == null) { return false; } return suggestionresults.hasmoreresults(); } public pagereference dosuggest() { nbresult = 5; suggestaccounts(); return null; } public pagereference dosuggestmore() { nbresult += 5; suggestaccounts(); return null; } private void suggestaccounts() { search.suggestionoption options = new search.suggestionoption(); search.knowledgesuggestionfilter filters = new search.knowledgesuggestionfilter(); if (objecttype=='knowledgearticleversion') { filters.setlanguage(language); filters.setpublishstatus('online'); } options.setfilter(filters); options.setlimit(nbresult); suggestionresults = search.suggest(searchtext, objecttype, options); } } see also: search.suggest(searchquery,sobjecttype,suggestions) salesforce files use apex to customize the behavior of salesforce files. 456apex developer guide using salesforce features with apex in this section: customize file downloads you can customize the behavior of files when users attempt to download them using an apex callback. contentversion supports modified file behavior, such as antivirus scanning and information rights management (irm), after the download operation. file download customization is available in api version 39.0 and later. custom file download examples you can use apex to customize the behavior of files upon attempted download. these examples assume that only one file is being downloaded. file download customization is available in api version 39.0 and later. customize file downloads you can customize the behavior of files when users attempt to download them using an apex callback. contentversion supports modified file behavior, such as antivirus scanning and information rights management (irm), after the download operation. file download customization is available in api version 39.0 and later. customization code runs before download and determines whether the download can proceed. the sfc namespace contains apex objects for customizing the behavior of salesforce files before they are downloaded. contentdownloadhandlerfactory provides an interface for customizing file downloads. the contentdownloadhandler class defines values related to whether download is allowed, and what to do otherwise. the contentdownloadcontext enum is the context in which the download takes place. you can use apex to customize multiple-file downloads from the content tab in salesforce classic. the apex function parameter list<id> handles a list of contentversion ids. customization also works on content packs and content deliveries. list<id> is a list of the version ids in a contentpack. setting isdownloadallowed = false on a multi-file or contentpack download causes the entire download to fail. you can pass a list of the problem files back to an error page via url parameters in redirecturl. example: • prevent a file from downloading based on the user profile, device being used, or file type and size. • apply irm control to track information, such as the number of times a file has been downloaded. • flag
suspicious files before download, and redirect them for antivirus scanning. flow execution when a download is triggered either from the ui, connect api, or an sobject call retrieving contentversion.versiondata, implementations of the sfc.contentdownloadhandlerfactory are looked up. if no implementation is found, download proceeds. otherwise, the user is redirected to what has been defined in the contentdownloadhandler#redirecturl property. if several implementations are found, they are cascade handled (ordered by name) and the first one for which the download isn’t allowed is considered. note: if a soap api operation triggers a download, it goes through the apex class that checks whether the download is allowed. if a download isn’t allowed, a redirection can’t be handled, and an exception containing an error message is returned instead. custom file download examples you can use apex to customize the behavior of files upon attempted download. these examples assume that only one file is being downloaded. file download customization is available in api version 39.0 and later. 457apex developer guide using salesforce features with apex example: this example demonstrates a system that requires downloads to go through irm control for some users. for a modify all data (mad) user who’s allowed to download files, and whose user id is 005xx: // allow customization of the content download experience public class contentdownloadhandlerfactoryimpl implements sfc.contentdownloadhandlerfactory { public sfc.contentdownloadhandler getcontentdownloadhandler(list<id> ids, sfc.contentdownloadcontext context) { sfc.contentdownloadhandler contentdownloadhandler = new sfc.contentdownloadhandler(); if(userinfo.getuserid() == '005xx') { contentdownloadhandler.isdownloadallowed = true; return contentdownloadhandler; } contentdownloadhandler.isdownloadallowed = false; contentdownloadhandler.downloaderrormessage = 'this file needs to be irm controlled. you're not allowed to download it'; contentdownloadhandler.redirecturl ='/apex/irmcontrol?id='+ids.get(0); return contentdownloadhandler; } } note: to refer to a mad user profile, you can use userinfo.getprofileid() instead of userinfo.getuserid(). in this example, irmcontrol is a visualforce page created for displaying a link to download a file from the irm system. you need a controller for this page that calls your irm system. as it’s processing the file, it gives an endpoint to download the file when it’s controlled. your irm system uses the sobject api to get the versiondata of this contentversion. therefore, the irm system needs the versionid and must retrieve the versiondata using the mad user. your irm system is at http://irmsystem and is expecting the versionid as a query parameter. the irm system returns a json response with the download endpoint in a downloadendpoint value. public class irmcontroller { private string downloadendpoint; public irmcontroller() { downloadendpoint = ''; } public void applyirmcontrol() { string versionid = apexpages.currentpage().getparameters().get('id'); http h = new http(); //instantiate a new http request, specify the method (get) as well as the endpoint httprequest req = new httprequest(); req.setendpoint('http://irmsystem?versionid=' + versionid); req.setmethod('get'); // send the request, and retrieve a response 458apex developer guide using salesforce features with apex httpresponse r = h.send(req); jsonparser parser = json.createparser(r.getbody()); while (parser.nexttoken() != null) { if ((parser.getcurrenttoken() == jsontoken.field_name) && (parser.gettext() == 'downloadendpoint')) { parser.nexttoken(); downloadendpoint = parser.gettext(); break; } } } public string getdownloadendpoint() { return downloadendpoint; } } example: the following example creates a class that implements the contentdownloadhandlerfactory interface and returns a download handler that prevents downloading a file to a mobile device. // allow customization of the content download experience public class contentdownloadhandlerfactoryimpl implements sfc.contentdownloadhandlerfactory { public sfc.contentdownloadhandler getcontentdownloadhandler(list<id> ids, sfc.contentdownloadcontext context) { sfc.contentdownload
handler contentdownloadhandler = new sfc.contentdownloadhandler(); if(context == sfc.contentdownloadcontext.mobile) { contentdownloadhandler.isdownloadallowed = false; contentdownloadhandler.downloaderrormessage = 'downloading a file from a mobile device isn't allowed.'; return contentdownloadhandler; } contentdownloadhandler.isdownloadallowed = true; return contentdownloadhandler; } example: you can also prevent downloading a file from a mobile device and require that a file must go through irm control. // allow customization of the content download experience public class contentdownloadhandlerfactoryimpl implements sfc.contentdownloadhandlerfactory { public sfc.contentdownloadhandler getcontentdownloadhandler(list<id> ids, sfc.contentdownloadcontext context) { sfc.contentdownloadhandler contentdownloadhandler = new sfc.contentdownloadhandler(); if(userinfo.getuserid() == '005xx000001svogaac') { contentdownloadhandler.isdownloadallowed = true; return contentdownloadhandler; 459apex developer guide using salesforce features with apex } if(context == sfc.contentdownloadcontext.mobile) { contentdownloadhandler.isdownloadallowed = false; contentdownloadhandler.downloaderrormessage = 'downloading a file from a mobile device isn't allowed.'; return contentdownloadhandler; } contentdownloadhandler.isdownloadallowed = false; contentdownloadhandler.downloaderrormessage = 'this file needs to be irm controlled. you're not allowed to download it'; contentdownloadhandler.redirecturl ='/apex/irmcontrol?id='+id.get(0); return contentdownloadhandler; } } salesforce connect apex code can access external object data via any salesforce connect adapter. use the apex connector framework to develop a custom adapter for salesforce connect. the custom adapter can retrieve data from external systems and synthesize data locally. salesforce connect represents that data in salesforce external objects, enabling users and the lightning platform to seamlessly interact with data that’s stored outside the salesforce org. in this section: apex considerations for salesforce connect external objects apex code can access external object data via any salesforce connect adapter, but some requirements and limitations apply. writable external objects by default, external objects are read only, but you can make them writable. doing so lets salesforce users and apis create, update, and delete data that’s stored outside the org by interacting with external objects within the org. for example, users can see all the orders that reside in an sap system that are associated with an account in salesforce. then, without leaving the salesforce user interface, they can place a new order or route an existing order. the relevant data is automatically created or updated in the sap system. external change data capture packaging and testing you can distribute external change data capture components in managed packages, including a framework for testing your apex triggers. special behaviors and limitations apply to packaging and package installation. get started with the apex connector framework to get started with your first custom adapter for salesforce connect, create two apex classes: one that extends the datasource.connection class, and one that extends the datasource.provider class. key concepts about the apex connector framework the datasource namespace provides the classes for the apex connector framework. use the apex connector framework to develop a custom adapter for salesforce connect. then connect your salesforce org to any data anywhere via the salesforce connect custom adapter. considerations for the apex connector framework understand the limits and considerations for creating salesforce connect custom adapters with the apex connector framework. 460apex developer guide using salesforce features with apex apex connector framework examples these examples illustrate how to use the apex connector framework to create custom adapters for salesforce connect. see also: salesforce help: access external data with salesforce connect salesforce connect learning map apex considerations for salesforce connect external objects apex code can access external object data via any salesforce connect adapter, but some requirements and limitations apply. • these features aren’t available for external objects. – apex-managed sharing – apex triggers (however, you can create triggers on external change data capture events from odata 4.0 connections.) • when developers use apex to manipulate external object records, asynchronous timing and an active background queue minimize potential save conflicts. a specialized set of apex methods and keywords handles potential timing issues with write execution. apex also lets you retrieve the results of delete and upsert operations. use the backgroundoperation object to
monitor job progress for write operations via the api or soql. • 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. important: when running an iterable batch apex job against an external data source, the external records are stored in salesforce while the job is running. the data is removed from storage when the job completes, whether or not the job was successful. no external data is stored during batch apex jobs that use database.querylocator. • if you use batch apex with database.querylocator to access external objects via an odata adapter for salesforce connect: – enable request row counts on the external data source, and each response from the external system must include the total row count of the result set. – we recommend enabling server driven pagination on the external data source and having the external system determine page sizes and batch boundaries for large result sets. typically, server-driven paging can adjust batch boundaries to accommodate changing data sets more effectively than client-driven paging. when server driven pagination is disabled on the external data source, the odata adapter controls the paging behavior (client-driven). if external object records are added to the external system while a job runs, other records can be processed twice. if external object records are deleted from the external system while a job runs, other records can be skipped. – when server driven pagination is enabled on the external data source, the batch size at runtime is the smaller of the following: • batch size specified in the scope parameter of database.executebatch. default is 200 records. • page size returned by the external system. we recommend that you set up your external system to return page sizes of 200 or fewer records. see also: using batch apex salesforce help: client-driven and server-driven paging for salesforce connect—odata 2.0 and 4.0 adapters salesforce help: define an external data source for salesforce connect—odata 2.0 or 4.0 adapter 461apex developer guide using salesforce features with apex writable external objects by default, external objects are read only, but you can make them writable. doing so lets salesforce users and apis create, update, and delete data that’s stored outside the org by interacting with external objects within the org. for example, users can see all the orders that reside in an sap system that are associated with an account in salesforce. then, without leaving the salesforce user interface, they can place a new order or route an existing order. the relevant data is automatically created or updated in the sap system. access to external data depends on the connections between salesforce and the external systems that store the data. network latency and the availability of the external systems can introduce timing issues with apex write or delete operations on external objects. because of the complexity of these connections, apex can’t execute standard insert(), update(), or create() operations on external objects. instead, apex provides a specialized set of database methods and keywords to work around potential issues with write execution. dml insert, update, create, and delete operations on external objects are either asynchronous or executed when specific criteria are met. this example uses the database.insertasync() method to insert a new order into a database table asynchronously. it returns a saveresult object that contains a unique identifier for the insert job. public void createorder () { salesorder__x order = new salesorder__x (); database.saveresult sr = database.insertasync (order); if (! sr.issuccess ()) { string locator = database.getasynclocator ( sr ); completeordercreation(locator); } } note: writes performed on external objects through the salesforce user interface or the api are synchronous and work the same way as for standard and custom objects. you can perform the following dml operations on external objects, either asynchronously or based on criteria: insert records, update records, upsert records, or delete records. use classes in the datasource namespace to get the unique identifiers for asynchronous jobs, or to retrieve results lists for upsert, delete, or save operations. when you initiate an apex method on an external object, a job is scheduled and placed in the background jobs queue. the backgroundoperation object lets you view the job status for write operations via the api or soql. monitor job progress and related errors in the org, extract statistics, process batch jobs, or see how many errors occur in a specified time period. for usage information and examples, see database
namespace and datasource namespace. see also: salesforce help: writable external objects considerations for salesforce connect—all adapters external change data capture packaging and testing you can distribute external change data capture components in managed packages, including a framework for testing your apex triggers. special behaviors and limitations apply to packaging and package installation. • include external change data tracking components in a managed package by selecting your test from the apex class component type list. the trigger, test, external data source, external object, and other related assets are brought into the package for distribution. • certificates aren’t packageable. if you package an external data source that specifies a certificate, make sure that the subscriber org has a valid certificate with the same name. to help you test your external change data capture–triggered apex classes, here is a unit test code example of a trigger reacting to a simulated external change. 462apex developer guide using salesforce features with apex example trigger trigger onexternalproductchangeeventforaudit on products__changeevent (after insert) { if (trigger.new.size() != 1) return; for (products__changeevent event: trigger.new) { product_audit__c audit = new product_audit__c(); audit.name = 'productchangeon' + event.externalid; audit.change_type__c = event.changeeventheader.getchangetype(); audit.audit_price__c = event.price__c; audit.product_name__c = event.name__c; insert(audit); } } apex test @istest public class testonexternalproductchangeeventforaudit { static testmethod void testexternalproductchangetrigger() { // create change event products__changeevent event = new products__changeevent(); // set change event header fields eventbus.changeeventheader header = new eventbus.changeeventheader(); header.changetype='create'; header.entityname='products__x'; header.changeorigin='here'; header.transactionkey = 'some'; header.commituser = 'me'; event.changeeventheader = header; event.put('externalid', 'parentexternalid'); event.put('price__c', 5500); event.put('name__c', 'coat'); // publish the event to the eventbus eventbus.publish(event); test.geteventbus().deliver(); // perform assertion that the trigger was run product_audit__c audit = [select name, audit_price__c, product_name__c from product_audit__c where name = : 'productchangeon'+ event.externalid limit 1]; system.assertequals('productchangeon'+ event.externalid, audit.name); system.assertequals(5500, audit.audit_price__c); system.assertequals('coat', audit.product_name__c); } } get started with the apex connector framework to get started with your first custom adapter for salesforce connect, create two apex classes: one that extends the datasource.connection class, and one that extends the datasource.provider class. let’s step through the code of a sample custom adapter. 463apex developer guide using salesforce features with apex in this section: 1. create a sample datasource.connection class first, create a datasource.connection class to enable salesforce to obtain the external system’s schema and to handle queries and searches of the external data. 2. create a sample datasource.provider class now you need a class that extends and overrides a few methods in datasource.provider. 3. set up salesforce connect to use your custom adapter after you create your datasource.connection and datasource.provider classes, the salesforce connect custom adapter becomes available in setup. create a sample datasource.connection class first, create a datasource.connection class to enable salesforce to obtain the external system’s schema and to handle queries and searches of the external data. global class sampledatasourceconnection extends datasource.connection { global sampledatasourceconnection(datasource.connectionparams connectionparams) { } // add implementation of abstract methods // ... the datasource.connection class contains these methods. • query • search • sync • upsertrows • deleterows sync the sync() method is invoked when an administrator clicks the validate and sync button on the external
data source detail page. it returns information that describes the structural metadata on the external system. note: changing the sync method on the datasource.connection class doesn’t automatically resync any external objects. // ... override global list<datasource.table> sync() { list<datasource.table> tables = new list<datasource.table>(); list<datasource.column> columns; columns = new list<datasource.column>(); columns.add(datasource.column.text('name', 255)); columns.add(datasource.column.text('externalid', 255)); columns.add(datasource.column.url('displayurl')); tables.add(datasource.table.get('sample', 'title', columns)); return tables; 464apex developer guide using salesforce features with apex } // ... query the query method is invoked when a soql query is executed on an external object. a soql query is automatically generated and executed when a user opens an external object’s list view or detail page in salesforce. the datasource.querycontext is always only for a single table. this sample custom adapter uses a helper method in the datasource.queryutils class to filter and sort the results based on the where and order by clauses in the soql query. the datasource.queryutils class and its helper methods can process query results locally within your salesforce org. this class is provided for your convenience to simplify the development of your salesforce connect custom adapter for initial tests. however, the datasource.queryutils class and its methods aren’t supported for use in production environments that use callouts to retrieve data from external systems. complete the filtering and sorting on the external system before sending the query results to salesforce. when possible, use server-driven paging or another technique to have the external system determine the appropriate data subsets according to the limit and offset clauses in the query. // ... override global datasource.tableresult query( datasource.querycontext context) { if (context.tableselection.columnsselected.size() == 1 && context.tableselection.columnsselected.get(0).aggregation == datasource.queryaggregation.count) { list<map<string,object>> rows = getrows(context); list<map<string,object>> response = datasource.queryutils.filter(context, getrows(context)); list<map<string, object>> countresponse = new list<map<string, object>>(); map<string, object> countrow = new map<string, object>(); countrow.put( context.tableselection.columnsselected.get(0).columnname, response.size()); countresponse.add(countrow); return datasource.tableresult.get(context, countresponse); } else { list<map<string,object>> filteredrows = datasource.queryutils.filter(context, getrows(context)); list<map<string,object>> sortedrows = datasource.queryutils.sort(context, filteredrows); list<map<string,object>> limitedrows = datasource.queryutils.applylimitandoffset(context, sortedrows); return datasource.tableresult.get(context, limitedrows); } } // ... 465apex developer guide using salesforce features with apex search the search method is invoked by a sosl query of an external object or when a user performs a salesforce global search that also searches external objects. because search can be federated over multiple objects, the datasource.searchcontext can have multiple tables selected. in this example, however, the custom adapter knows about only one table. // ... override global list<datasource.tableresult> search( datasource.searchcontext context) { list<datasource.tableresult> results = new list<datasource.tableresult>(); for (datasource.tableselection tableselection : context.tableselections) { results.add(datasource.tableresult.get(tableselection, getrows(context))); } return results; } // ... the following is the getrows helper method that the search sample calls to get row values from the external system. the getrows method makes use of other helper methods: • makegetcallout makes a callout to the external system. •
foundrow populates a row based on values from the callout result. the foundrow method is used to make any modifications to the returned field values, such as changing a field name or modifying a field value. these methods aren’t included in this snippet but are available in the full example included in connection class. typically, the filter from searchcontext or querycontext would be used to reduce the result set, but for simplicity this example doesn’t make use of the context object. // ... // helper method to get record values from the external system for the sample table. private list<map<string, object>> getrows () { // get row field values for the sample table from the external system via a callout. httpresponse response = makegetcallout(); // parse the json response and populate the rows. map<string, object> m = (map<string, object>)json.deserializeuntyped( response.getbody()); map<string, object> error = (map<string, object>)m.get('error'); if (error != null) { throwexception(string.valueof(error.get('message'))); } list<map<string,object>> rows = new list<map<string,object>>(); list<object> jsonrows = (list<object>)m.get('value'); if (jsonrows == null) { rows.add(foundrow(m)); } else { for (object jsonrow : jsonrows) { map<string,object> row = (map<string,object>)jsonrow; rows.add(foundrow(row)); } } return rows; 466apex developer guide using salesforce features with apex } // ... upsertrows the upsertrows method is invoked when external object records are created or updated. you can create or update external object records through the salesforce user interface or dml. the following example provides a sample implementation for the upsertrows method. the example uses the passed-in upsertcontext to determine what table was selected and performs the upsert only if the name of the selected table is sample. the upsert operation is broken up into either an insert of a new record or an update of an existing record. these operations are performed in the external system using callouts. an array of datasource.upsertresult is populated from the results obtained from the callout responses. note that because a callout is made for each row, this example might hit the apex callouts limit. // ... global override list<datasource.upsertresult> upsertrows(datasource.upsertcontext context) { if (context.tableselected == 'sample') { list<datasource.upsertresult> results = new list<datasource.upsertresult>(); list<map<string, object>> rows = context.rows; for (map<string, object> row : rows){ // make a callout to insert or update records in the external system. httpresponse response; // determine whether to insert or update a record. if (row.get('externalid') == null){ // send a post http request to insert new external record. // make an apex callout and get httpresponse. response = makepostcallout( '{"name":"' + row.get('name') + '","externalid":"' + row.get('externalid') + '"'); } else { // send a put http request to update an existing external record. // make an apex callout and get httpresponse. response = makeputcallout( '{"name":"' + row.get('name') + '","externalid":"' + row.get('externalid') + '"', string.valueof(row.get('externalid'))); } // check the returned response. // deserialize the response. map<string, object> m = (map<string, object>)json.deserializeuntyped( response.getbody()); if (response.getstatuscode() == 200){ results.add(datasource.upsertresult.success( string.valueof(m.get('id')))); } else { results.add(datasource.upsertresult.failure( string.valueof(m.get('id')), 'the callout resulted in an error: ' + response.getstatuscode())); 467apex developer guide using salesforce features with apex }
} return results; } return null; } // ... deleterows the deleterows method is invoked when external object records are deleted. you can delete external object records through the salesforce user interface or dml. the following example provides a sample implementation for the deleterows method. the example uses the passed-in deletecontext to determine what table was selected and performs the deletion only if the name of the selected table is sample. the deletion is performed in the external system using callouts for each external id. an array of datasource.deleteresult is populated from the results obtained from the callout responses. note that because a callout is made for each id, this example might hit the apex callouts limit. // ... global override list<datasource.deleteresult> deleterows(datasource.deletecontext context) { if (context.tableselected == 'sample'){ list<datasource.deleteresult> results = new list<datasource.deleteresult>(); for (string externalid : context.externalids){ httpresponse response = makedeletecallout(externalid); if (response.getstatuscode() == 200){ results.add(datasource.deleteresult.success(externalid)); } else { results.add(datasource.deleteresult.failure(externalid, 'callout delete error:' + response.getbody())); } } return results; } return null; } // ... see also: execution governors and limits apex reference guide: connection class filters in the apex connector framework create a sample datasource.provider class now you need a class that extends and overrides a few methods in datasource.provider. your datasource.provider class informs salesforce of the functional and authentication capabilities that are supported by or required to connect to the external system. global class sampledatasourceprovider extends datasource.provider { 468apex developer guide using salesforce features with apex if the external system requires authentication, salesforce can provide the authentication credentials from the external data source definition or users’ personal settings. for simplicity, however, this example declares that the external system doesn’t require authentication. to do so, it returns authenticationcapability.anonymous as the sole entry in the list of authentication capabilities. override global list<datasource.authenticationcapability> getauthenticationcapabilities() { list<datasource.authenticationcapability> capabilities = new list<datasource.authenticationcapability>(); capabilities.add( datasource.authenticationcapability.anonymous); return capabilities; } this example also declares that the external system allows soql queries, sosl queries, salesforce searches, upserting data, and deleting data. • to allow soql, the example declares the datasource.capability.row_query capability. • to allow sosl and salesforce searches, the example declares the datasource.capability.search capability. • to allow upserting external data, the example declares the datasource.capability.row_create and datasource.capability.row_update capabilities. • to allow deleting external data, the example declares the datasource.capability.row_delete capability. override global list<datasource.capability> getcapabilities() { list<datasource.capability> capabilities = new list<datasource.capability>(); capabilities.add(datasource.capability.row_query); capabilities.add(datasource.capability.search); capabilities.add(datasource.capability.row_create); capabilities.add(datasource.capability.row_update); capabilities.add(datasource.capability.row_delete); return capabilities; } lastly, the example identifies the sampledatasourceconnection class that obtains the external system’s schema and handles the queries and searches of the external data. override global datasource.connection getconnection( datasource.connectionparams connectionparams) { return new sampledatasourceconnection(connectionparams); } } see also: apex reference guide: provider class set up salesforce connect to use your custom adapter after you create your datasource.connection and datasource.provider classes, the salesforce connect custom adapter becomes available in setup. complete the tasks that are described in “set up salesforce connect to access external data with a custom adapter” in the salesforce help.
469apex developer guide using salesforce features with apex to add write capability for external objects to your adapter: 1. make the external data source for this adapter writable. see “define an external data source for salesforce connect—custom adapter” in the salesforce help. 2. implement the datasource.connection.upsertrows() and datasource.connection.deleterows() methods for the adapter. for details, see connection class. key concepts about the apex connector framework the datasource namespace provides the classes for the apex connector framework. use the apex connector framework to develop a custom adapter for salesforce connect. then connect your salesforce org to any data anywhere via the salesforce connect custom adapter. we recommend that you learn about some key concepts to help you use the apex connector framework effectively. in this section: external ids for salesforce connect external objects when you access external data with a custom adapter for salesforce connect, the values of the external id standard field on an external object come from the datasource.column named externalid. authentication for salesforce connect custom adapters your datasource.provider class declares what types of credentials can be used to authenticate to the external system. callouts for salesforce connect custom adapters just like any other apex code, a salesforce connect custom adapter can make callouts. if the connection to the external system requires authentication, incorporate the authentication parameters into the callout. paging with the apex connector framework when displaying a large set of records in the user interface, salesforce breaks the set into batches and displays one batch. you can then page through those batches. however, custom adapters for salesforce connect don’t automatically support paging of any kind. to support paging through external object data that’s obtained by a custom adapter, implement server-driven or client-driven paging. querymore with the apex connector framework custom adapters for salesforce connect don’t automatically support the querymore method in api queries. however, your implementation must be able to break up large result sets into batches and iterate over them by using the querymore method in the soap api. the default batch size is 500 records, but the query developer can adjust that value programmatically in the query call. aggregation for salesforce connect custom adapters if you receive a count() query, the selected column has the value queryaggregation.count in its aggregation property. the selected column is provided in the columnsselected property on the tableselection for the datasource.querycontext. filters in the apex connector framework the datasource.querycontext contains one datasource.tableselection. the datasource.searchcontext can have more than one tableselection. each tableselection has a filter property that represents the where clause in a soql or sosl query. external ids for salesforce connect external objects when you access external data with a custom adapter for salesforce connect, the values of the external id standard field on an external object come from the datasource.column named externalid. 470apex developer guide using salesforce features with apex each external object has an external id standard field. its values uniquely identify each external object record in your org. when the external object is the parent in an external lookup relationship, the external id standard field is used to identify the child records. important: • the custom adapter’s apex code must declare the datasource.column named externalid and provide its values. • don’t use sensitive data as the values of the external id standard field or fields designated as name fields, because salesforce sometimes stores those values. – external lookup relationship fields on child records store and display the external id values of the parent records. – for internal use only, salesforce stores the external id value of each row that’s retrieved from the external system.this behavior doesn’t apply to external objects that are associated with high-data-volume external data sources. example: this excerpt from a sample datasource.connection class shows the datasource.column named externalid. override global list<datasource.table> sync() { list<datasource.table> tables = new list<datasource.table>(); list<datasource.column> columns; columns = new list<datasource.column>(); columns.add(datasource.column.text('title', 255)); columns.add(datasource.column.text('description',255)); columns.add(datasource.column.text('createddate',255)); columns.add(datasource.column.text('modifieddate',255
)); columns.add(datasource.column.url('selflink')); columns.add(datasource.column.url('displayurl')); columns.add(datasource.column.text('externalid',255)); tables.add(datasource.table.get('googledrive','title', columns)); return tables; } see also: apex reference guide: column class authentication for salesforce connect custom adapters your datasource.provider class declares what types of credentials can be used to authenticate to the external system. if your extension of the datasource.provider class returns datasource.authenticationcapability values that indicate support for authentication, the datasource.connection class is instantiated with a datasource.connectionparams instance in the constructor. the authentication credentials in the datasource.connectionparams instance depend on the identity type field of the external data source definition in salesforce. • if identity type is set to named principal, the credentials come from the external data source definition. • if identity type is set to per user: – for queries and searches, the credentials are specific to the current user who invokes the query or search. the credentials come from the user’s authentication settings for the external system. 471apex developer guide using salesforce features with apex – for administrative connections, such as syncing the external system’s schema, the credentials come from the external data source definition. in this section: oauth for salesforce connect custom adapters if you use oauth 2.0 to access external data, learn how to avoid access interruptions caused by expired access tokens. see also: oauth for salesforce connect custom adapters oauth for salesforce connect custom adapters if you use oauth 2.0 to access external data, learn how to avoid access interruptions caused by expired access tokens. some external systems use oauth access tokens that expire and need to be refreshed. we can automatically refresh access tokens as needed when: • the user or external data source has a valid refresh token from a previous oauth flow. • the sync, query, or search method in your datasource.connection class throws a datasource.oauthtokenexpiredexception. we use the relevant oauth credentials for the user or external data source to negotiate with the remote service and refresh the token. the datasource.connection class is reconstructed with the new oauth token in the datasource.connectionparams that we supply to the constructor. the search or query is then reinvoked. if the authentication provider doesn’t provide a refresh token, access to the external system is lost when the current access token expires. if a warning message appears on the external data source detail page, consult your oauth provider for information about requesting offline access or a refresh token. for some authentication providers, requesting offline access is as simple as adding a scope. for example, to request offline access from a salesforce authentication provider, add refresh_token to the default scopes field on the authentication provider definition in your salesforce organization. for other authentication providers, you must request offline access in the authentication url as a query parameter. for example, with google, append ?access_type=offline to the authorize endpoint url field on the authentication provider definition in your salesforce organization. to edit the authorization endpoint, select open id connect in the provider type field of the authentication provider. for details, see “configure an openid connect authentication provider” in the salesforce help. see also: authentication for salesforce connect custom adapters callouts for salesforce connect custom adapters just like any other apex code, a salesforce connect custom adapter can make callouts. if the connection to the external system requires authentication, incorporate the authentication parameters into the callout. authentication parameters are encapsulated in a connectionparams object and provided to your datasource.connection class’s constructor. 472apex developer guide using salesforce features with apex for example, if your connection requires an oauth access token, use code similar to the following. public httpresponse getresponse(string url) { http httpprotocol = new http(); httprequest request = new httprequest(); request.setendpoint(url); request.setmethod('get'); request.setheader('authorization', 'bearer ' + this.connectioninfo.oauthtoken); httpresponse response = httpprotocol.send(request); return response; } if your connection requires basic password authentication, use code similar to the following. public httpresponse getresponse(string url) { http httpprotocol = new h
ttp(); httprequest request = new httprequest(); request.setendpoint(url); request.setmethod('get'); string encodedheadervalue = encodingutil.base64encode(blob.valueof( this.connectioninfo.username + ':' + this.connectioninfo.password)); request.setheader('authorization', 'basic ' + encodedheadervalue); httpresponse response = httpprotocol.send(request); return response; } named credentials as callout endpoints for salesforce connect custom adapters a salesforce connect custom adapter obtains the relevant credentials that are stored in salesforce whenever they’re needed. however, your apex code must apply those credentials to all callouts, except those that specify named credentials as the callout endpoints. a named credential lets salesforce handle the authentication logic for you so that your code doesn’t have to. if all your custom adapter’s callouts use named credentials, you can set the external data source’s authentication protocol field to no authentication. the named credentials add the appropriate certificates and can add standard authorization headers to the callouts. you also don’t need to define a remote site for an apex callout endpoint that’s defined as a named credential. see also: named credentials as callout endpoints paging with the apex connector framework when displaying a large set of records in the user interface, salesforce breaks the set into batches and displays one batch. you can then page through those batches. however, custom adapters for salesforce connect don’t automatically support paging of any kind. to support paging through external object data that’s obtained by a custom adapter, implement server-driven or client-driven paging. with server-driven paging, the external system controls the paging and ignores any batch boundaries or page sizes that are specified in queries. to enable server-driven paging, declare the query_pagination_server_driven capability in your datasource.provider class. also, your apex code must generate a query token and use it to determine and fetch the next batch of results. with client-driven paging, you use limit and offset clauses to page through result sets. factor in the offset and maxresults properties in the datasource.querycontext to determine which rows to return. for example, suppose that the result set has 473apex developer guide using salesforce features with apex 20 rows with numeric externalid values from 1 to 20. if we ask for an offset of 5 and maxresults of 5, we expect to get the rows with ids 6–10. we recommend that you do all filtering in the external system, outside of apex, using methods that the external system supports. see also: apex reference guide: querycontext class querymore with the apex connector framework custom adapters for salesforce connect don’t automatically support the querymore method in api queries. however, your implementation must be able to break up large result sets into batches and iterate over them by using the querymore method in the soap api. the default batch size is 500 records, but the query developer can adjust that value programmatically in the query call. to support querymore, your implementation must indicate whether more data exists than what’s in the current batch. when the lightning platform knows that more data exists, your api queries return a queryresult object that’s similar to the following. { "totalsize" => -1, "done" => false, "nextrecordsurl" => "/services/data/v32.0/query/01gxx000000b5ogaak-2000", "records" => [ [ 0] { "attributes" => { "type" => "sample__x", "url" => "/services/data/v32.0/sobjects/sample__x/x06xx0000000001aaa" }, "externalid" => "id0" }, [ 1] { "attributes" => { "type" => "sample__x", "url" => "/services/data/v32.0/sobjects/sample__x/x06xx0000000002aaa" }, … } in this section: support querymore by using server-driven paging with server-driven paging, the external system controls the paging and ignores any batch boundaries or page sizes that are specified in queries. to enable server-driven paging, declare the query_pagination_server_driven capability in
your datasource.provider class. support querymore by using client-driven paging with client-driven paging, you use limit and offset clauses to page through result sets. 474apex developer guide using salesforce features with apex support querymore by using server-driven paging with server-driven paging, the external system controls the paging and ignores any batch boundaries or page sizes that are specified in queries. to enable server-driven paging, declare the query_pagination_server_driven capability in your datasource.provider class. when the returned datasource.tableresult doesn’t contain the entire result set, the tableresult must provide a querymoretoken value. the query token is an arbitrary string that we store temporarily. when we request the next batch of results, we pass the query token back to your custom adapter in the datasource.querycontext. your apex code must use that query token to determine which rows belong to the next batch of results. when your custom adapter returns the final batch, it must not return a querymoretoken value in the tableresult. see also: querymore with the apex connector framework support querymore by using client-driven paging with client-driven paging, you use limit and offset clauses to page through result sets. if the external system can return the total size of the result set for each query, declare the query_total_size capability in your datasource.provider class. make sure that each search or query returns the totalsize value in the datasource.tableresult. if the total size is larger than the number of rows that are returned in the batch, we generate a nextrecordsurl link and set the done flag to false. we also set the totalsize in the tableresult to the value that you supply. if the external system can’t return the total size for each query, don’t declare the query_total_size capability in your datasource.provider class. whenever we do a query through your custom adapter, we ask for one extra row. for example, if you run the query select externalid from sample limit 5, we call the query method on the datasource.connection object with a datasource.querycontext that has the maxresults property set to 6. the presence or absence of that sixth row in the result set indicates whether more data is available. we assume, however, that the data set we query against doesn’t change between queries. if the data set changes between queries, you might see repeated rows or not get all results. ultimately, accessing external data works most efficiently when you retrieve small amounts of data and the data set that you query against changes infrequently. see also: querymore with the apex connector framework aggregation for salesforce connect custom adapters if you receive a count() query, the selected column has the value queryaggregation.count in its aggregation property. the selected column is provided in the columnsselected property on the tableselection for the datasource.querycontext. the following example illustrates how to apply the value of the aggregation property to handle count() queries. // handle count() queries if (context.tableselection.columnsselected.size() == 1 && context.tableselection.columnsselected.get(0).aggregation == queryaggregation.count) { list<map<string, object>> countresponse = new list<map<string, object>>(); 475apex developer guide using salesforce features with apex map<string, object> countrow = new map<string, object>(); countrow.put(context.tableselection.columnsselected.get(0).columnname, response.size()); countresponse.add(countrow); return countresponse; } an aggregate query can still have filters, so your query method can be implemented like the following example to support basic aggregation queries, with or without filters. override global datasource.tableresult query(datasource.querycontext context) { list<map<string,object>> rows = retrievedata(context); list<map<string,object>> response = postfilterrecords( context.tableselection.filter, rows); if (context.tableselection.columnsselected.size() == 1 && context.tableselection.columnsselected.get(0).aggregation == datasource.queryaggregation.count) { list<map<string, object>> countresponse = new list<map<string, object>>(); map<string, object>
countrow = new map<string, object>(); countrow.put(context.tableselection.columnsselected.get(0).columnname, response.size()); countresponse.add(countrow); return datasource.tableresult.get(context, countresponse); } return datasource.tableresult.get(context, response); } see also: apex reference guide: querycontext class create a sample datasource.connection class filters in the apex connector framework the datasource.querycontext contains one datasource.tableselection. the datasource.searchcontext can have more than one tableselection. each tableselection has a filter property that represents the where clause in a soql or sosl query. for example, when a user goes to an external object’s record detail page, your datasource.connection is executed. behind the scenes, we generate a soql query similar to the following. select columnnames from externalobjectapiname where externalid = 'selectedexternalobjectexternalid' this soql query causes the query method on your datasource.connection class to be invoked. the following code can detect this condition. if (context.tableselection.filter != null) { if (context.tableselection.filter.type == datasource.filtertype.equals && 'externalid' == context.tableselection.filter.columnname && context.tableselection.filter.columnvalue instanceof string) { string selection = (string)context.tableselection.filter.columnvalue; return datasource.tableresult.get(true, null, 476apex developer guide using salesforce features with apex tableselection.tableselected, findsingleresult(selection)); } } this code example assumes that you implemented a findsingleresult method that returns a single record, given the selected externalid. make sure that your code obtains the record that matches the requested externalid. in this section: evaluating filters in the apex connector framework a filter evaluates to true for a row if that row matches the conditions that the filter describes. compound filters in the apex connector framework filters can have child filters, which are stored in the subfilters property. evaluating filters in the apex connector framework a filter evaluates to true for a row if that row matches the conditions that the filter describes. for example, suppose that a datasource.filter has columnname set to meaningoflife, columnvalue set to 42, and type set to equals. any row in the remote table whose meaningoflife column entry equals 42 is returned. suppose, instead, that the filter has type set to less_than, columnvalue set to 3, and columnname set to numericcol. we’d construct a datasource.tableresult object that contains all the rows that have a numericcol value less than 3. to improve performance, do all the filtering in the external system. you can, for example, translate the filter object into a sql or odata query, or map it to parameters on a soap query. if the external system returns a large set of data, and you do the filtering in your apex code, you quickly exceed your governor limits. if you can’t do all the filtering in the external system, do as much as possible there and return as little data as possible. then filter the smaller collection of data in your apex code. see also: apex reference guide: filter class compound filters in the apex connector framework filters can have child filters, which are stored in the subfilters property. if a filter has children, the filter type must be one of the following. filter type description and_ we return all rows that match all of the subfilters. or_ we return all rows that match any of the subfilters. not_ the filter reverses how its child filter evaluates rows. filters of this type can have only one subfilter. this code example illustrates how to deal with compound filters. override global datasource.tableresult query(datasource.querycontext context) { // call out to an external data source and retrieve a set of records. // we should attempt to get as much information as possible about the 477apex developer guide using salesforce features with apex // query from the querycontext, to minimize the number of records // that we return. list<map<string,object>> rows = retrievedata(context); // this only filters the results. anything in the query that we don’t // currently support, such as aggregation
or sorting, is ignored. return datasource.tableresult.get(context, postfilterrecords( context.tableselection.filter, rows)); } private list<map<string,object>> retrievedata(datasource.querycontext context) { // call out to an external data source. form the callout so that // it filters as much as possible on the remote site, // based on the parameters in the querycontext. return ...; } private list<map<string,object>> postfilterrecords( datasource.filter filter, list<map<string,object>> rows) { if (filter == null) { return rows; } datasource.filtertype type = filter.type; list<map<string,object>> retainedrows = new list<map<string,object>>(); if (type == datasource.filtertype.not_) { // we expect one filter in the subfilters. datasource.filter subfilter = filter.subfilters.get(0); for (map<string,object> row : rows) { if (!evaluate(filter, row)) { retainedrows.add(row); } } return retainedrows; } else if (type == datasource.filtertype.and_) { // for each filter, find all matches; anything that matches all filters // is returned. retainedrows = rows; for (datasource.filter subfilter : filter.subfilters) { retainedrows = postfilterrecords(subfilter, retainedrows); } return retainedrows; } else if (type == datasource.filtertype.or_) { // for each filter, find all matches. anything that matches // at least one filter is returned. for (datasource.filter subfilter : filter.subfilters) { list<map<string,object>> matchedrows = postfilterrecords( subfilter, rows); retainedrows.addall(matchedrows); } return retainedrows; } else { // find all matches for this filter in our collection of records. for (map<string,object> row : rows) { if (evaluate(filter, row)) { 478apex developer guide using salesforce features with apex retainedrows.add(row); } } return retainedrows; } } private boolean evaluate(datasource.filter filter, map<string,object> row) { if (filter.type == datasource.filtertype.equals) { string columnname = filter.columnname; object expectedvalue = filter.columnvalue; object foundvalue = row.get(columnname); return expectedvalue.equals(foundvalue); } else { // throw an exception; implementing other filter types is left // as an exercise for the reader. throwexception('unexpected filter type: ' + filter.type); } return false; } see also: apex reference guide: filter class considerations for the apex connector framework understand the limits and considerations for creating salesforce connect custom adapters with the apex connector framework. • if you change and save a datasource.connection class, resave the corresponding datasource.provider class. otherwise, when you define the external data source, the custom adapter doesn’t appear as an option for the type field. also, the associated external objects’ custom tabs no longer appear in the salesforce ui. • dml operations aren’t allowed in the apex code that comprises the custom adapter. • make sure that you understand the limits of the external system’s apis. for example, some external systems accept only requests for up to 40 rows. • apex data type limitations: – double—the value loses precision beyond 18 significant digits. for higher precision, use decimals instead of doubles. – string—if the length is greater than 255 characters, the string is mapped to a long text area field in salesforce. • custom adapters for salesforce connect are subject to the same limitations as any other apex code. for example: – all apex governor limits apply. – test methods don’t support web service callouts. tests that perform web service callouts fail. for an example that shows how to avoid these failing tests by returning mock responses, see google drive™ custom adapter for salesforce connect on page 480. • in apex tests, use dynamic soql to query external objects. tests that perform static soql queries of external objects fail. see also: dynamic soql 479apex developer guide using
salesforce features with apex apex connector framework examples these examples illustrate how to use the apex connector framework to create custom adapters for salesforce connect. in this section: google drive™ custom adapter for salesforce connect this example illustrates how to use callouts and oauth to connect to an external system, which in this case is the google drive™ online storage service. the example also shows how to avoid failing tests from web service callouts by returning mock responses for test methods. google books™ custom adapter for salesforce connect this example illustrates how to work around the requirements and limits of an external system’s apis: in this case, the google books api family. loopback custom adapter for salesforce connect this example illustrates how to handle filtering in queries. for simplicity, this example connects the salesforce org to itself as the external system. github custom adapter for salesforce connect this example illustrates how to support indirect lookup relationships. an indirect lookup relationship links a child external object to a parent standard or custom object. stack overflow custom adapter for salesforce connect this example illustrates how to support external lookup relationships and multiple tables. an external lookup relationship links a child standard, custom, or external object to a parent external object. each table can become an external object in the salesforce org. google drive™ custom adapter for salesforce connect this example illustrates how to use callouts and oauth to connect to an external system, which in this case is the google drive™ online storage service. the example also shows how to avoid failing tests from web service callouts by returning mock responses for test methods. for this example to work reliably, request offline access when setting up oauth so that salesforce can obtain and maintain a refresh token for your connections. drivedatasourceconnection class /** * extends the datasource.connection class to enable * salesforce to sync the external system’s schema * and to handle queries and searches of the external data. **/ global class drivedatasourceconnection extends datasource.connection { private datasource.connectionparams connectioninfo; /** * constructor for drivedatasourceconnection. **/ global drivedatasourceconnection( datasource.connectionparams connectioninfo) { this.connectioninfo = connectioninfo; 480apex developer guide using salesforce features with apex } /** * called when an external object needs to get a list of * schema from the external data source, for example when * the administrator clicks “validate and sync” in the * user interface for the external data source. **/ override global list<datasource.table> sync() { list<datasource.table> tables = new list<datasource.table>(); list<datasource.column> columns; columns = new list<datasource.column>(); columns.add(datasource.column.text('title', 255)); columns.add(datasource.column.text('description',255)); columns.add(datasource.column.text('createddate',255)); columns.add(datasource.column.text('modifieddate',255)); columns.add(datasource.column.url('selflink')); columns.add(datasource.column.url('displayurl')); columns.add(datasource.column.text('externalid',255)); tables.add(datasource.table.get('googledrive','title', columns)); return tables; } /** * called to query and get results from the external * system for soql queries, list views, and detail pages * for an external object that’s associated with the * external data source. * * the querycontext argument represents the query to run * against a table in the external system. * * returns a list of rows as the query results. **/ override global datasource.tableresult query( datasource.querycontext context) { datasource.filter filter = context.tableselection.filter; string url; if (filter != null) { string thiscolumnname = filter.columnname; if (thiscolumnname != null && thiscolumnname.equals('externalid')) url = 'https://www.googleapis.com/drive/v2/' + 'files/' + filter.columnvalue; else url = 'https://www.googleapis.com/drive/v2/' + 'files'; } else { url = 'https://www.googleapis.com/drive/v2/' + '
files'; } 481apex developer guide using salesforce features with apex /** * filters, sorts, and applies limit and offset clauses. **/ list<map<string, object>> rows = datasource.queryutils.process(context, getdata(url)); return datasource.tableresult.get(true, null, context.tableselection.tableselected, rows); } /** * called to do a full text search and get results from * the external system for sosl queries and salesforce * global searches. * * the searchcontext argument represents the query to run * against a table in the external system. * * returns results for each table that the searchcontext * requested to be searched. **/ override global list<datasource.tableresult> search( datasource.searchcontext context) { list<datasource.tableresult> results = new list<datasource.tableresult>(); for (integer i =0;i< context.tableselections.size();i++) { string entity = context.tableselections[i].tableselected; string url = 'https://www.googleapis.com/drive/v2/files'+ '?q=fulltext+contains+\''+context.searchphrase+'\''; results.add(datasource.tableresult.get( true, null, entity, getdata(url))); } return results; } /** * helper method to parse the data. * the url argument is the url of the external system. * returns a list of rows from the external system. **/ public list<map<string, object>> getdata(string url) { string response = getresponse(url); list<map<string, object>> rows = new list<map<string, object>>(); map<string, object> responsebodymap = (map<string, object>) json.deserializeuntyped(response); /** * checks errors. **/ 482apex developer guide using salesforce features with apex map<string, object> error = (map<string, object>)responsebodymap.get('error'); if (error!=null) { list<object> errorslist = (list<object>)error.get('errors'); map<string, object> errors = (map<string, object>)errorslist[0]; string errormessage = (string)errors.get('message'); throw new datasource.oauthtokenexpiredexception(errormessage); } list<object> fileitems=(list<object>)responsebodymap.get('items'); if (fileitems != null) { for (integer i=0; i < fileitems.size(); i++) { map<string, object> item = (map<string, object>)fileitems[i]; rows.add(createrow(item)); } } else { rows.add(createrow(responsebodymap)); } return rows; } /** * helper method to populate the external id and display * url fields on external object records based on the 'id' * value that’s sent by the external system. * * the map<string, object> item parameter maps to the data * that represents a row. * * returns an updated map with the external id and * display url values. **/ public map<string, object> createrow( map<string, object> item){ map<string, object> row = new map<string, object>(); for ( string key : item.keyset() ) { if (key == 'id') { row.put('externalid', item.get(key)); } else if (key=='selflink') { row.put(key, item.get(key)); row.put('displayurl', item.get(key)); } else { row.put(key, item.get(key)); } } return row; } static string mockresponse = '{' + ' "kind": "drive#file",' + 483apex developer guide using salesforce features with apex ' "id": "12345",' + ' "selflink": "files/12345",' + ' "title": "mock file",' + ' "mimetype": "application/text",' + ' "description": "mock response that’s used during tests",' + ' "createddate": "2016-
04-20",' + ' "modifieddate": "2016-04-20",' + ' "version": 1' + '}'; /** * helper method to make the http get call. * the url argument is the url of the external system. * returns the response from the external system. **/ public string getresponse(string url) { if (system.test.isrunningtest()) { // avoid callouts during tests. return mock data instead. return mockresponse; } else { // perform callouts for production (non-test) results. http httpprotocol = new http(); httprequest request = new httprequest(); request.setendpoint(url); request.setmethod('get'); request.setheader('authorization', 'bearer '+ this.connectioninfo.oauthtoken); httpresponse response = httpprotocol.send(request); return response.getbody(); } } } drivedatasourceprovider class /** * extends the datasource.provider base class to create a * custom adapter for salesforce connect. the class informs * salesforce of the functional and authentication * capabilities that are supported by or required to connect * to an external system. **/ global class drivedatasourceprovider extends datasource.provider { /** * declares the types of authentication that can be used * to access the external system. **/ override global list<datasource.authenticationcapability> getauthenticationcapabilities() { list<datasource.authenticationcapability> capabilities = new list<datasource.authenticationcapability>(); capabilities.add( 484apex developer guide using salesforce features with apex datasource.authenticationcapability.oauth); capabilities.add( datasource.authenticationcapability.anonymous); return capabilities; } /** * declares the functional capabilities that the * external system supports. **/ override global list<datasource.capability> getcapabilities() { list<datasource.capability> capabilities = new list<datasource.capability>(); capabilities.add(datasource.capability.row_query); capabilities.add(datasource.capability.search); return capabilities; } /** * declares the associated datasource.connection class. **/ override global datasource.connection getconnection( datasource.connectionparams connectionparams) { return new drivedatasourceconnection(connectionparams); } } google books™ custom adapter for salesforce connect this example illustrates how to work around the requirements and limits of an external system’s apis: in this case, the google books api family. to integrate with the google books™ service, we set up salesforce connect as follows. • the google books api allows a maximum of 40 returned results, so we develop our custom adapter to handle result sets with more than 40 rows. • the google books api can sort only by search relevance and publish dates, so we develop our custom adapter to disable sorting on columns. • to support oauth, we set up our authentication settings in salesforce so that the requested scope of permissions for access tokens includes https://www.googleapis.com/auth/books. • to allow apex callouts, we define these remote sites in salesforce: – https://www.googleapis.com – https://books.google.com booksdatasourceconnection class /** * extends the datasource.connection class to enable * salesforce to sync the external system metadata * schema and to handle queries and searches of the external 485apex developer guide using salesforce features with apex * data. **/ global class booksdatasourceconnection extends datasource.connection { private datasource.connectionparams connectioninfo; // constructor for booksdatasourceconnection. global booksdatasourceconnection(datasource.connectionparams connectioninfo) { this.connectioninfo = connectioninfo; } /** * called when an external object needs to get a list of * schema from the external data source, for example when * the administrator clicks “validate and sync” in the * user interface for the external data source. **/ override global list<datasource.table> sync() { list<datasource.table> tables = new list<datasource.table>(); list<datasource.column> columns; columns = new list<datasource.column>(); columns.add
(getcolumn('title')); columns.add(getcolumn('description')); columns.add(getcolumn('publisheddate')); columns.add(getcolumn('publisher')); columns.add(datasource.column.url('displayurl')); columns.add(datasource.column.text('externalid', 255)); tables.add(datasource.table.get('googlebooks', 'title', columns)); return tables; } /** * google books api v1 doesn't support sorting, * so we create a column with sortable = false. **/ private datasource.column getcolumn(string columnname) { datasource.column column = datasource.column.text(columnname, 255); column.sortable = false; return column; } /** * called to query and get results from the external * system for soql queries, list views, and detail pages * for an external object that's associated with the * external data source. * * the querycontext argument represents the query to run * against a table in the external system. 486apex developer guide using salesforce features with apex * * returns a list of rows as the query results. **/ override global datasource.tableresult query( datasource.querycontext contexts) { datasource.filter filter = contexts.tableselection.filter; string url; if (contexts.tableselection.columnsselected.size() == 1 && contexts.tableselection.columnsselected.get(0).aggregation == datasource.queryaggregation.count) { return getcount(contexts); } if (filter != null) { string thiscolumnname = filter.columnname; if (thiscolumnname != null && thiscolumnname.equals('externalid')) { url = 'https://www.googleapis.com/books/v1/' + 'volumes?q=' + filter.columnvalue + '&maxresults=1&id=' + filter.columnvalue; return datasource.tableresult.get(true, null, contexts.tableselection.tableselected, getdata(url)); } else { url = 'https://www.googleapis.com/books/' + 'v1/volumes?q=' + filter.columnvalue + '&id=' + filter.columnvalue + '&maxresults=40' + '&startindex='; } } else { url = 'https://www.googleapis.com/books/v1/' + 'volumes?q=america&' + '&maxresults=40' + '&startindex='; } /** * google books api v1 supports maxresults of 40 * so we handle pagination explicitly in the else statement * when we handle more than 40 records per query. **/ if (contexts.maxresults < 40) { return datasource.tableresult.get(true, null, contexts.tableselection.tableselected, getdata(url + contexts.offset)); } else { return fetchdata(contexts, url); } } /** * helper method to fetch results when maxresults is * greater than 40 (the max value for maxresults supported * by google books api v1). 487apex developer guide using salesforce features with apex **/ private datasource.tableresult fetchdata( datasource.querycontext contexts, string url) { integer fetchslot = (contexts.maxresults / 40) + 1; list<map<string, object>> data = new list<map<string, object>>(); integer startindex = contexts.offset; for(integer count = 0; count < fetchslot; count++) { data.addall(getdata(url + startindex)); if(count == 0) contexts.offset = 41; else contexts.offset += 40; } return datasource.tableresult.get(true, null, contexts.tableselection.tableselected, data); } /** * helper method to execute count() query. **/ private datasource.tableresult getcount( datasource.querycontext contexts) { string url = 'https://www.googleapis.com/books/v1/' + 'volumes?q=america&projection=full'; list<map<string,object
>> response = datasource.queryutils.filter(contexts, getdata(url)); list<map<string, object>> countresponse = new list<map<string, object>>(); map<string, object> countrow = new map<string, object>(); countrow.put( contexts.tableselection.columnsselected.get(0).columnname, response.size()); countresponse.add(countrow); return datasource.tableresult.get(contexts, countresponse); } /** * called to do a full text search and get results from * the external system for sosl queries and salesforce * global searches. * * the searchcontext argument represents the query to run * against a table in the external system. * * returns results for each table that the searchcontext * requested to be searched. **/ override global list<datasource.tableresult> search( datasource.searchcontext contexts) { list<datasource.tableresult> results = new list<datasource.tableresult>(); 488apex developer guide using salesforce features with apex for (integer i =0; i< contexts.tableselections.size();i++) { string entity = contexts.tableselections[i].tableselected; string url = 'https://www.googleapis.com/books/v1' + '/volumes?q=' + contexts.searchphrase; results.add(datasource.tableresult.get(true, null, entity, getdata(url))); } return results; } /** * helper method to parse the data. * returns a list of rows from the external system. **/ public list<map<string, object>> getdata(string url) { httpresponse response = getresponse(url); string body = response.getbody(); list<map<string, object>> rows = new list<map<string, object>>(); map<string, object> responsebodymap = (map<string, object>)json.deserializeuntyped(body); /** * checks errors. **/ map<string, object> error = (map<string, object>)responsebodymap.get('error'); if (error!=null) { list<object> errorslist = (list<object>)error.get('errors'); map<string, object> errors = (map<string, object>)errorslist[0]; string messages = (string)errors.get('message'); throw new datasource.oauthtokenexpiredexception(messages); } list<object> sitems = (list<object>)responsebodymap.get('items'); if (sitems != null) { for (integer i=0; i< sitems.size(); i++) { map<string, object> item = (map<string, object>)sitems[i]; rows.add(createrow(item)); } } else { rows.add(createrow(responsebodymap)); } return rows; } 489apex developer guide using salesforce features with apex /** * helper method to populate a row based on source data. * * the item argument maps to the data that * represents a row. * * returns an updated map with the external id and * display url values. **/ public map<string, object> createrow( map<string, object> item) { map<string, object> row = new map<string, object>(); for ( string key : item.keyset() ){ if (key == 'id') { row.put('externalid', item.get(key)); } else if (key == 'volumeinfo') { map<string, object> volumeinfomap = (map<string, object>)item.get(key); row.put('title', volumeinfomap.get('title')); row.put('description', volumeinfomap.get('description')); row.put('displayurl', volumeinfomap.get('infolink')); row.put('publisheddate', volumeinfomap.get('publisheddate')); row.put('publisher', volumeinfomap.get('publisher')); } } return row; } /** * helper method to make the http get call. * the url argument is the url of the external system. * returns the response from the external system. **/ public http
response getresponse(string url) { http httpprotocol = new http(); httprequest request = new httprequest(); request.setendpoint(url); request.setmethod('get'); request.setheader('authorization', 'bearer '+ this.connectioninfo.oauthtoken); httpresponse response = httpprotocol.send(request); return response; } } booksdatasourceprovider class /** * extends the datasource.provider base class to create a 490apex developer guide using salesforce features with apex * custom adapter for salesforce connect. the class informs * salesforce of the functional and authentication * capabilities that are supported by or required to connect * to an external system. **/ global class booksdatasourceprovider extends datasource.provider { /** * declares the types of authentication that can be used * to access the external system. **/ override global list<datasource.authenticationcapability> getauthenticationcapabilities() { list<datasource.authenticationcapability> capabilities = new list<datasource.authenticationcapability>(); capabilities.add( datasource.authenticationcapability.oauth); capabilities.add( datasource.authenticationcapability.anonymous); return capabilities; } /** * declares the functional capabilities that the * external system supports. **/ override global list<datasource.capability> getcapabilities() { list<datasource.capability> capabilities = new list<datasource.capability>(); capabilities.add(datasource.capability.row_query); capabilities.add(datasource.capability.search); return capabilities; } /** * declares the associated datasource.connection class. **/ override global datasource.connection getconnection( datasource.connectionparams connectionparams) { return new booksdatasourceconnection(connectionparams); } } loopback custom adapter for salesforce connect this example illustrates how to handle filtering in queries. for simplicity, this example connects the salesforce org to itself as the external system. loopbackdatasourceconnection class /** * extends the datasource.connection class to enable 491apex developer guide using salesforce features with apex * salesforce to sync the external system’s schema * and to handle queries and searches of the external data. **/ global class loopbackdatasourceconnection extends datasource.connection { /** * constructors. **/ global loopbackdatasourceconnection( datasource.connectionparams connectionparams) { } global loopbackdatasourceconnection() {} /** * called when an external object needs to get a list of * schema from the external data source, for example when * the administrator clicks “validate and syncâ€(cid:0) in the * user interface for the external data source. **/ override global list<datasource.table> sync() { list<datasource.table> tables = new list<datasource.table>(); list<datasource.column> columns; columns = new list<datasource.column>(); columns.add(datasource.column.text('externalid', 255)); columns.add(datasource.column.url('displayurl')); columns.add(datasource.column.text('name', 255)); columns.add( datasource.column.number('numberofemployees', 18, 0)); tables.add( datasource.table.get('looper', 'name', columns)); return tables; } /** * called to query and get results from the external * system for soql queries, list views, and detail pages * for an external object that’s associated with the * external data source. * * the querycontext argument represents the query to run * against a table in the external system. * * returns a list of rows as the query results. **/ override global datasource.tableresult query(datasource.querycontext context) { if (context.tableselection.columnsselected.size() == 1 && context.tableselection.columnsselected.get(0).aggregation == datasource.queryaggregation.count) { integer count = execcount(getcountquery(context)); list<map<string, object>> countresponse = new list<map<string,
object>>(); 492apex developer guide using salesforce features with apex map<string, object> countrow = new map<string, object>(); countrow.put( context.tableselection.columnsselected.get(0).columnname, count); countresponse.add(countrow); return datasource.tableresult.get(context,countresponse); } else { list<map<string,object>> rows = execquery( getsoqlquery(context)); return datasource.tableresult.get(context,rows); } } /** * called to do a full text search and get results from * the external system for sosl queries and salesforce * global searches. * * the searchcontext argument represents the query to run * against a table in the external system. * * returns results for each table that the searchcontext * requested to be searched. **/ override global list<datasource.tableresult> search(datasource.searchcontext context) { return datasource.searchutils.searchbyname(context, this); } /** * helper method to execute the soql query and * return the results. **/ private list<map<string,object>> execquery(string soqlquery) { list<account> objs = database.query(soqlquery); list<map<string,object>> rows = new list<map<string,object>>(); for (account obj : objs) { map<string,object> row = new map<string,object>(); row.put('name', obj.name); row.put('numberofemployees', obj.numberofemployees); row.put('externalid', obj.id); row.put('displayurl', url.getsalesforcebaseurl().toexternalform() + obj.id); rows.add(row); } return rows; } /** * helper method to get aggregate count. 493apex developer guide using salesforce features with apex **/ private integer execcount(string soqlquery) { integer count = database.countquery(soqlquery); return count; } /** * helper method to create default aggregate query. **/ private string getcountquery(datasource.querycontext context) { string basequery = 'select count() from account'; string filter = getsoqlfilter('', context.tableselection.filter); if (filter.length() > 0) return basequery + ' where ' + filter; return basequery; } /** * helper method to create default query. **/ private string getsoqlquery(datasource.querycontext context) { string basequery = 'select id,name,numberofemployees from account'; string filter = getsoqlfilter('', context.tableselection.filter); if (filter.length() > 0) return basequery + ' where ' + filter; return basequery; } /** * helper method to handle query filter. **/ private string getsoqlfilter(string query, datasource.filter filter) { if (filter == null) { return query; } string append; datasource.filtertype type = filter.type; list<map<string,object>> retainedrows = new list<map<string,object>>(); if (type == datasource.filtertype.not_) { datasource.filter subfilter = filter.subfilters.get(0); append = getsoqlfilter('not', subfilter); } else if (type == datasource.filtertype.and_) { append = getsoqlfiltercompound('and', filter.subfilters); } else if (type == datasource.filtertype.or_) { append = getsoqlfiltercompound('or', filter.subfilters); } else { append = getsoqlfilterexpression(filter); 494apex developer guide using salesforce features with apex } return query + ' ' + append; } /** * helper method to handle query subfilters. **/ private string getsoqlfiltercompound(string operator, list<datasource.filter> subfilters) { string expression = ' ('; boolean first = true; for (datasource.filter subfilter : subfilters) { if (first) first = false; else expression += ' ' + operator
+ ' '; expression += getsoqlfilter('', subfilter); } expression += ') '; return expression; } /** * helper method to handle query filter expressions. **/ private string getsoqlfilterexpression( datasource.filter filter) { string columnname = filter.columnname; string operator; object expectedvalue = filter.columnvalue; if (filter.type == datasource.filtertype.equals) { operator = '='; } else if (filter.type == datasource.filtertype.not_equals) { operator = '<>'; } else if (filter.type == datasource.filtertype.less_than) { operator = '<'; } else if (filter.type == datasource.filtertype.greater_than) { operator = '>'; } else if (filter.type == datasource.filtertype.less_than_or_equal_to) { operator = '<='; } else if (filter.type == datasource.filtertype.greater_than_or_equal_to) { operator = '>='; } else if (filter.type == datasource.filtertype.starts_with) { return mapcolumnname(columnname) + ' like \'' + string.valueof(expectedvalue) + '%\''; } else if (filter.type == datasource.filtertype.ends_with) { return mapcolumnname(columnname) + 495apex developer guide using salesforce features with apex ' like \'%' + string.valueof(expectedvalue) + '\''; } else if (filter.type == datasource.filtertype.like_) { return mapcolumnname(columnname) + ' like \'' + string.valueof(expectedvalue) + '\''; } else { throwexception( 'implementing other filter types is left as an exercise for the reader: ' + filter.type); } return mapcolumnname(columnname) + ' ' + operator + ' ' + wrapvalue(expectedvalue); } /** * helper method to map column names. **/ private string mapcolumnname(string apexname) { if (apexname.equalsignorecase('externalid')) return 'id'; if (apexname.equalsignorecase('displayurl')) return 'id'; return apexname; } /** * helper method to wrap expression strings with quotes. **/ private string wrapvalue(object foundvalue) { if (foundvalue instanceof string) return '\'' + string.valueof(foundvalue) + '\''; return string.valueof(foundvalue); } } loopbackdatasourceprovider class /** * extends the datasource.provider base class to create a * custom adapter for salesforce connect. the class informs * salesforce of the functional and authentication * capabilities that are supported by or required to connect * to an external system. **/ global class loopbackdatasourceprovider extends datasource.provider { /** * declares the types of authentication that can be used * to access the external system. **/ override global list<datasource.authenticationcapability> getauthenticationcapabilities() { list<datasource.authenticationcapability> capabilities = 496
apex developer guide using salesforce features with apex new list<datasource.authenticationcapability>(); capabilities.add( datasource.authenticationcapability.anonymous); capabilities.add( datasource.authenticationcapability.basic); return capabilities; } /** * declares the functional capabilities that the * external system supports. **/ override global list<datasource.capability> getcapabilities() { list<datasource.capability> capabilities = new list<datasource.capability>(); capabilities.add(datasource.capability.row_query); capabilities.add(datasource.capability.search); return capabilities; } /** * declares the associated datasource.connection class. **/ override global datasource.connection getconnection(datasource.connectionparams connectionparams) { return new loopbackdatasourceconnection(); } } github custom adapter for salesforce connect this example illustrates how to support indirect lookup relationships. an indirect lookup relationship links a child external object to a parent standard or custom object. for this example to work, create a custom field on the contact standard object. name the custom field github_username, make it a text field of length 39, and select the external id and unique attributes. also, add https://api.github.com to your remote site settings. githubdatasourceconnection class /** * defines the connection to github rest api v3 to support * querying of github profiles. * extends the datasource.connection class to enable * salesforce to sync the external system’s schema * and to handle queries and searches of the external data. **/ global class githubdatasourceconnection extends datasource.connection { private datasource.connectionparams connectioninfo; /** 497apex developer guide using salesforce features with apex * constructor for githubdatasourceconnection **/ global githubdatasourceconnection( datasource.connectionparams connectioninfo) { this.connectioninfo = connectioninfo; } /** * called to query and get results from the external * system for soql queries, list views, and detail pages * for an external object that’s associated with the * external data source. * * the querycontext argument represents the query to run * against a table in the external system. * * returns a list of rows as the query results. **/ override global datasource.tableresult query( datasource.querycontext context) { datasource.filter filter = context.tableselection.filter; string url; if (filter != null) { string thiscolumnname = filter.columnname; if (thiscolumnname != null && (thiscolumnname.equals('externalid') || thiscolumnname.equals('login'))) url = 'https://api.github.com/users/' + filter.columnvalue; else url = 'https://api.github.com/users'; } else { url = 'https://api.github.com/users'; } /** * filters, sorts, and applies limit and offset clauses. **/ list<map<string, object>> rows = datasource.queryutils.process(context, getdata(url)); return datasource.tableresult.get(true, null, context.tableselection.tableselected, rows); } /** * defines the schema for the external system. * called when the administrator clicks “validate and sync” * in the user interface for the external data source. **/ override global list<datasource.table> sync() { list<datasource.table> tables = new list<datasource.table>(); list<datasource.column> columns; columns = new list<datasource.column>(); 498apex developer guide using salesforce features with apex // defines the indirect lookup field. (for this to work, // make sure your contact standard object has a // custom unique, external id field called github_username.) columns.add(datasource.column.indirectlookup( 'login', 'contact', 'github_username__c')); columns.add(datasource.column.text('id', 255)); columns.add(datasource.column.text('name',255)); columns.add(datasource.column.text('company',255)); columns.add(datasource
.column.text('bio',255)); columns.add(datasource.column.text('followers',255)); columns.add(datasource.column.text('following',255)); columns.add(datasource.column.url('html_url')); columns.add(datasource.column.url('displayurl')); columns.add(datasource.column.text('externalid',255)); tables.add(datasource.table.get('githubprofile','login', columns)); return tables; } /** * called to do a full text search and get results from * the external system for sosl queries and salesforce * global searches. * * the searchcontext argument represents the query to run * against a table in the external system. * * returns results for each table that the searchcontext * requested to be searched. **/ override global list<datasource.tableresult> search( datasource.searchcontext context) { list<datasource.tableresult> results = new list<datasource.tableresult>(); for (integer i =0;i< context.tableselections.size();i++) { string entity = context.tableselections[i].tableselected; // search usernames string url = 'https://api.github.com/users/' + context.searchphrase; results.add(datasource.tableresult.get( true, null, entity, getdata(url))); } return results; } /** * helper method to parse the data. * the url argument is the url of the external system. * returns a list of rows from the external system. 499apex developer guide using salesforce features with apex **/ public list<map<string, object>> getdata(string url) { string response = getresponse(url); // standardize response string if (!response.contains('"items":')) { if (response.substring(0,1).equals('{')) { response = '[' + response + ']'; } response = '{"items": ' + response + '}'; } list<map<string, object>> rows = new list<map<string, object>>(); map<string, object> responsebodymap = (map<string, object>) json.deserializeuntyped(response); /** * checks errors. **/ map<string, object> error = (map<string, object>)responsebodymap.get('error'); if (error!=null) { list<object> errorslist = (list<object>)error.get('errors'); map<string, object> errors = (map<string, object>)errorslist[0]; string errormessage = (string)errors.get('message'); throw new datasource.oauthtokenexpiredexception(errormessage); } list<object> fileitems = (list<object>)responsebodymap.get('items'); if (fileitems != null) { for (integer i=0; i < fileitems.size(); i++) { map<string, object> item = (map<string, object>)fileitems[i]; rows.add(createrow(item)); } } else { rows.add(createrow(responsebodymap)); } return rows; } /** * helper method to populate the external id and display * url fields on external object records based on the 'id' * value that’s sent by the external system. * * the map<string, object> item parameter maps to the data 500apex developer guide using salesforce features with apex * that represents a row. * * returns an updated map with the external id and * display url values. **/ public map<string, object> createrow( map<string, object> item){ map<string, object> row = new map<string, object>(); for ( string key : item.keyset() ) { if (key == 'login') { row.put('externalid', item.get(key)); } else if (key=='html_url') { row.put('displayurl', item.get(key)); } row.put(key, item.get(key)); } return row; } /** * helper method to make the http get call. * the url argument is the url of the external system.
* returns the response from the external system. **/ public string getresponse(string url) { // perform callouts for production (non-test) results. http httpprotocol = new http(); httprequest request = new httprequest(); request.setendpoint(url); request.setmethod('get'); httpresponse response = httpprotocol.send(request); return response.getbody(); } } githubdatasourceprovider class /** * extends the datasource.provider base class to create a * custom adapter for salesforce connect. the class informs * salesforce of the functional and authentication * capabilities that are supported by or required to connect * to an external system. **/ global class githubdatasourceprovider extends datasource.provider { /** * for simplicity, this example declares that the external * system doesn’t require authentication by returning * authenticationcapability.anonymous as the sole entry * in the list of authentication capabilities. **/ 501apex developer guide using salesforce features with apex override global list<datasource.authenticationcapability> getauthenticationcapabilities() { list<datasource.authenticationcapability> capabilities = new list<datasource.authenticationcapability>(); capabilities.add( datasource.authenticationcapability.anonymous); return capabilities; } /** * declares the functional capabilities that the * external system supports, in this case * only soql queries. **/ override global list<datasource.capability> getcapabilities() { list<datasource.capability> capabilities = new list<datasource.capability>(); capabilities.add(datasource.capability.row_query); return capabilities; } /** * declares the associated datasource.connection class. **/ override global datasource.connection getconnection( datasource.connectionparams connectionparams) { return new githubdatasourceconnection(connectionparams); } } see also: adding remote site settings stack overflow custom adapter for salesforce connect this example illustrates how to support external lookup relationships and multiple tables. an external lookup relationship links a child standard, custom, or external object to a parent external object. each table can become an external object in the salesforce org. for this example to work, create a custom field on the contact standard object. name the custom field “github_username” and select the external id and unique attributes. stackoverflowdatasourceconnection class /** * defines the connection to stack exchange api v2.2 to support * querying of stack overflow users (stackoverflowuser) * and posts (stackoverflowpost). * extends the datasource.connection class to enable * salesforce to sync the external system’s schema * and to handle queries of the external data. **/ global class stackoverflowdatasourceconnection extends 502apex developer guide using salesforce features with apex datasource.connection { private datasource.connectionparams connectioninfo; /** * constructor for stackoverflowdatasourceconnection **/ global stackoverflowdatasourceconnection( datasource.connectionparams connectioninfo) { this.connectioninfo = connectioninfo; } /** * defines the schema for the external system. * called when the administrator clicks “validate and sync” * in the user interface for the external data source. **/ override global list<datasource.table> sync() { list<datasource.table> tables = new list<datasource.table>(); // defines columns for the table of stack overflow posts list<datasource.column> postcolumns = new list<datasource.column>(); // defines the external lookup field. postcolumns.add(datasource.column.externallookup( 'owner_id', 'stackoverflowuser__x')); postcolumns.add(datasource.column.text('title', 255)); postcolumns.add(datasource.column.text('view_count', 255)); postcolumns.add(datasource.column.text('question_id',255)); postcolumns.add(datasource.column.text('creation_date',255)); postcolumns.add(datasource.column.text('score',255)); postcolumns.add(datasource.column.url('link')); postcolumns.add(datasource.column.url
('displayurl')); postcolumns.add(datasource.column.text('externalid',255)); tables.add(datasource.table.get('stackoverflowpost','title', postcolumns)); // defines columns for the table of stack overflow users list<datasource.column> usercolumns = new list<datasource.column>(); usercolumns.add(datasource.column.text('user_id', 255)); usercolumns.add(datasource.column.text('display_name', 255)); usercolumns.add(datasource.column.text('location',255)); usercolumns.add(datasource.column.text('creation_date',255)); usercolumns.add(datasource.column.url('website_url',255)); usercolumns.add(datasource.column.text('reputation',255)); usercolumns.add(datasource.column.url('link')); usercolumns.add(datasource.column.url('displayurl')); usercolumns.add(datasource.column.text('externalid',255)); tables.add(datasource.table.get('stackoverflowuser', 'display_name', usercolumns)); 503apex developer guide using salesforce features with apex return tables; } /** * called to query and get results from the external * system for soql queries, list views, and detail pages * for an external object that’s associated with the * external data source. * * the querycontext argument represents the query to run * against a table in the external system. * * returns a list of rows as the query results. **/ override global datasource.tableresult query( datasource.querycontext context) { datasource.filter filter = context.tableselection.filter; string url; // sets the url to query stack overflow posts if (context.tableselection.tableselected .equals('stackoverflowpost')) { if (filter != null) { string thiscolumnname = filter.columnname; if (thiscolumnname != null && thiscolumnname.equals('externalid')) url = 'https://api.stackexchange.com/2.2/' + 'questions/' + filter.columnvalue + '?order=desc&sort=activity' + '&site=stackoverflow'; else url = 'https://api.stackexchange.com/2.2/' + 'questions' + '?order=desc&sort=activity' + '&site=stackoverflow'; } else { url = 'https://api.stackexchange.com/2.2/' + 'questions' + '?order=desc&sort=activity' + '&site=stackoverflow'; } // sets the url to query stack overflow users } else if (context.tableselection.tableselected .equals('stackoverflowuser')) { if (filter != null) { string thiscolumnname = filter.columnname; if (thiscolumnname != null && thiscolumnname.equals('externalid')) url = 'https://api.stackexchange.com/2.2/' + 'users/' + filter.columnvalue + '?order=desc&sort=reputation' + '&site=stackoverflow'; else 504apex developer guide using salesforce features with apex url = 'https://api.stackexchange.com/2.2/' + 'users' + '?order=desc&sort=reputation&site=stackoverflow'; } else { url = 'https://api.stackexchange.com/2.2/' + 'users' + '?order=desc&sort=reputation' + '&site=stackoverflow'; } } /** * filters, sorts, and applies limit and offset clauses. **/ list<map<string, object>> rows = datasource.queryutils.process(context, getdata(url)); return datasource.tableresult.get(true, null, context.tableselection.tableselected, rows); } /** * helper method to parse the data. * the url argument is the url of the external system. * returns a list of rows from the external
system. **/ public list<map<string, object>> getdata(string url) { string response = getresponse(url); list<map<string, object>> rows = new list<map<string, object>>(); map<string, object> responsebodymap = (map<string, object>) json.deserializeuntyped(response); /** * checks errors. **/ map<string, object> error = (map<string, object>)responsebodymap.get('error'); if (error!=null) { list<object> errorslist = (list<object>)error.get('errors'); map<string, object> errors = (map<string, object>)errorslist[0]; string errormessage = (string)errors.get('message'); throw new datasource.oauthtokenexpiredexception(errormessage); } list<object> fileitems= (list<object>)responsebodymap.get('items'); if (fileitems != null) { for (integer i=0; i < fileitems.size(); i++) { map<string, object> item = (map<string, object>)fileitems[i]; 505apex developer guide using salesforce features with apex rows.add(createrow(item)); } } else { rows.add(createrow(responsebodymap)); } return rows; } /** * helper method to populate the external id and display * url fields on external object records based on the 'id' * value that’s sent by the external system. * * the map<string, object> item parameter maps to the data * that represents a row. * * returns an updated map with the external id and * display url values. **/ public map<string, object> createrow( map<string, object> item) { map<string, object> row = new map<string, object>(); for ( string key : item.keyset() ) { if (key.equals('question_id') || key.equals('user_id')) { row.put('externalid', item.get(key)); } else if (key.equals('link')) { row.put('displayurl', item.get(key)); } else if (key.equals('owner')) { map<string, object> ownermap = (map<string, object>)item.get(key); row.put('owner_id', ownermap.get('user_id')); } row.put(key, item.get(key)); } return row; } /** * helper method to make the http get call. * the url argument is the url of the external system. * returns the response from the external system. **/ public string getresponse(string url) { // perform callouts for production (non-test) results. http httpprotocol = new http(); httprequest request = new httprequest(); request.setendpoint(url); request.setmethod('get'); httpresponse response = httpprotocol.send(request); return response.getbody(); } } 506apex developer guide using salesforce features with apex stackoverflowpostdatasourceprovider class /** * extends the datasource.provider base class to create a * custom adapter for salesforce connect. the class informs * salesforce of the functional and authentication * capabilities that are supported by or required to connect * to an external system. **/ global class stackoverflowpostdatasourceprovider extends datasource.provider { /** * for simplicity, this example declares that the external * system doesn’t require authentication by returning * authenticationcapability.anonymous as the sole entry * in the list of authentication capabilities. **/ override global list<datasource.authenticationcapability> getauthenticationcapabilities() { list<datasource.authenticationcapability> capabilities = new list<datasource.authenticationcapability>(); capabilities.add( datasource.authenticationcapability.anonymous); return capabilities; } /** * declares the functional capabilities that the * external system supports, in this case * only soql queries. **/ override global list<datasource.capability> getcapabilities() { list<datasource.capability> capabilities = new list<datasource.capability>(); capabilities
.add(datasource.capability.row_query); return capabilities; } /** * declares the associated datasource.connection class. **/ override global datasource.connection getconnection( datasource.connectionparams connectionparams) { return new stackoverflowdatasourceconnection(connectionparams); } } salesforce reports and dashboards api via apex the salesforce reports and dashboards api via apex gives you programmatic access to your report data as defined in the report builder. 507apex developer guide using salesforce features with apex the api enables you to integrate report data into any web or mobile application, inside or outside the salesforce platform. for example, you might use the api to trigger a chatter post with a snapshot of top-performing reps each quarter. the salesforce reports and dashboards api via apex revolutionizes the way that you access and visualize your data. you can: • integrate report data into custom objects. • integrate report data into rich visualizations to animate the data. • build custom dashboards. • automate reporting tasks. at a high level, the api resources enable you to query and filter report data. you can: • run tabular, summary, or matrix reports synchronously or asynchronously. • filter for specific data on the fly. • query report data and metadata. in this section: requirements and limitations the salesforce reports and dashboards api via apex is available for organizations that have api enabled. run reports you can run a report synchronously or asynchronously through the salesforce reports and dashboards api via apex. list asynchronous runs of a report you can retrieve up to 2,000 instances of a report that you ran asynchronously. get report metadata you can retrieve report metadata to get information about a report and its report type. get report data you can use the reportresults class to get the fact map, which contains data that’s associated with a report. filter reports to get specific results on the fly, you can filter reports through the api. decode the fact map the fact map contains the summary and record-level data values for a report. test reports like all apex code, salesforce reports and dashboards api via apex code requires test coverage. see also: apex reference guide: reports namespace requirements and limitations the salesforce reports and dashboards api via apex is available for organizations that have api enabled. the following restrictions apply to the reports and dashboards api via apex, in addition to general api limits. • cross filters, standard report filters, and filtering by row limit are unavailable when filtering data. • historical tracking reports are only supported for matrix reports. • subscriptions aren't supported for historical tracking reports. • the api can process only reports that contain up to 100 fields selected as columns. 508apex developer guide using salesforce features with apex • a list of up to 200 recently viewed reports can be returned. • your org can request up to 500 synchronous report runs per hour. • the api supports up to 20 synchronous report run requests at a time. • a list of up to 2,000 instances of a report that was run asynchronously can be returned. • the api supports up to 200 requests at a time to get results of asynchronous report runs. • your organization can request up to 1,200 asynchronous requests per hour. • asynchronous report run results are available within a 24-hour rolling period. • the api returns up to the first 2,000 report rows. you can narrow results using filters. • you can add up to 20 custom field filters when you run a report. • if a report is run on a standard or custom object as an automated process user from an apex test class, only the required custom fields are returned. non-required custom fields aren’t shown in the results. • – your org can request up to 200 dashboard refreshes per hour. – your org can request results for up to 5,000 dashboards per hour. in addition, the following restrictions apply to the reports and dashboards api via apex. • asynchronous report calls are not allowed in batch apex. • report calls are not allowed in apex triggers. • there is no apex method to list recently run reports. • the number of report rows processed during a synchronous report run count towards the governor limit that restricts the total number of rows retrieved by soql queries to 50,000 rows per transaction. this limit is not imposed when reports are run asynchronously. • in apex tests, report runs always ignore the seealldata annotation, regardless of whether the annotation is set to true or false. this means
that report results will include pre-existing data that the test didn’t create. there is no way to disable the seealldata annotation for a report execution. to limit results, use a filter on the report. • in apex tests, asynchronous report runs will execute only after the test is stopped using the test.stoptest method. note: all limits that apply to reports created in the report builder also apply to the api. for more information, see “analytics limits” in the salesforce online help. run reports you can run a report synchronously or asynchronously through the salesforce reports and dashboards api via apex. reports can be run with or without details and can be filtered by setting report metadata. when you run a report, the api returns data for the same number of records that are available when the report is run in the salesforce user interface. run a report synchronously if you expect it to finish running quickly. otherwise, we recommend that you run reports through the salesforce api asynchronously for these reasons: • long-running reports have a lower risk of reaching the timeout limit when they are run asynchronously. • the two-minute overall salesforce api timeout limit doesn’t apply to asynchronous runs. • the salesforce reports and dashboards api via apex can handle a higher number of asynchronous run requests at a time. • because the results of an asynchronously run report are stored for a 24-hour rolling period, they’re available for recurring access. 509apex developer guide using salesforce features with apex example: run a report synchronously to run a report synchronously, use one of the reportmanager.runreport() methods. for example: // get the report id list <report> reportlist = [select id,developername from report where developername = 'closed_sales_this_quarter']; string reportid = (string)reportlist.get(0).get('id'); // run the report reports.reportresults results = reports.reportmanager.runreport(reportid, true); system.debug('synchronous results: ' + results); example: run a report asynchronously to run a report asynchronously, use one of the reportmanager.runasyncreport() methods. for example: // get the report id list <report> reportlist = [select id,developername from report where developername = 'closed_sales_this_quarter']; string reportid = (string)reportlist.get(0).get('id'); // run the report reports.reportinstance instance = reports.reportmanager.runasyncreport(reportid, true); system.debug('asynchronous instance: ' + instance); list asynchronous runs of a report you can retrieve up to 2,000 instances of a report that you ran asynchronously. the instance list is sorted by the date and time when the report was run. report results are stored for a rolling 24-hour period. during this time, based on your user access level, you can access results for each instance of the report that was run. example: you can get the instance list by calling the reportmanager.getreportinstances method. for example: // get the report id list <report> reportlist = [select id,developername from report where developername = 'closed_sales_this_quarter']; string reportid = (string)reportlist.get(0).get('id'); // run a report asynchronously reports.reportinstance instance = reports.reportmanager.runasyncreport(reportid, true); system.debug('list of asynchronous runs: ' + reports.reportmanager.getreportinstances(reportid)); get report metadata you can retrieve report metadata to get information about a report and its report type. metadata includes information about fields that are used in the report for filters, groupings, detailed data, and summaries. you can use the metadata to do several things: • find out what fields and values you can filter on in the report type. • build custom chart visualizations by using the metadata information on fields, groupings, detailed data, and summaries. • change filters in the report metadata when you run a report. 510apex developer guide using salesforce features with apex use the reportresults.getreportmetadata method to retrieve report metadata. you can then use the “get” methods on the reportmetadata class to access metadata values. example: the following example retrieves metadata for a report. // get the report id list <report> reportlist = [select id,developername from report where developername = 'cl
osed_sales_this_quarter']; string reportid = (string)reportlist.get(0).get('id'); // run a report reports.reportresults results = reports.reportmanager.runreport(reportid); // get the report metadata reports.reportmetadata rm = results.getreportmetadata(); system.debug('name: ' + rm.getname()); system.debug('id: ' + rm.getid()); system.debug('currency code: ' + rm.getcurrencycode()); system.debug('developer name: ' + rm.getdevelopername()); // get grouping info for first grouping reports.groupinginfo ginfo = rm.getgroupingsdown()[0]; system.debug('grouping name: ' + ginfo.getname()); system.debug('grouping sort order: ' + ginfo.getsortorder()); system.debug('grouping date granularity: ' + ginfo.getdategranularity()); // get aggregates system.debug('first aggregate: ' + rm.getaggregates()[0]); system.debug('second aggregate: ' + rm.getaggregates()[1]); // get detail columns system.debug('detail columns: ' + rm.getdetailcolumns()); // get report format system.debug('report format: ' + rm.getreportformat()); get report data you can use the reportresults class to get the fact map, which contains data that’s associated with a report. example: to access data values of the fact map, you can map grouping value keys to the corresponding fact map keys. in the following example, imagine that you have an opportunity report that’s grouped by close month, and you’ve summarized the amount field. to get the value for the summary amount for the first grouping in the report: 1. get the first down-grouping in the report by using the reportresults.getgroupingsdown method and accessing the first groupingvalue object. 2. get the grouping key value from the groupingvalue object by using the getkey method. 3. construct a fact map key by appending '!t'to this key value. the resulting fact map key represents the summary value for the first down-grouping. 4. get the fact map from the report results by using the fact map key. 5. get the first summary amount value by using the reportfact.getaggregates method and accessing the first summaryvalue object. 511apex developer guide using salesforce features with apex 6. get the field value from the first data cell of the first row of the report by using the reportfactwithdetails.getrows method. // get the report id list <report> reportlist = [select id,developername from report where developername = 'closed_sales_this_quarter']; string reportid = (string)reportlist.get(0).get('id'); // run a report synchronously reports.reportresults results = reports.reportmanager.runreport(reportid, true); // get the first down-grouping in the report reports.dimension dim = results.getgroupingsdown(); reports.groupingvalue groupingval = dim.getgroupings()[0]; system.debug('key: ' + groupingval.getkey()); system.debug('label: ' + groupingval.getlabel()); system.debug('value: ' + groupingval.getvalue()); // construct a fact map key, using the grouping key value string factmapkey = groupingval.getkey() + '!t'; // get the fact map from the report results reports.reportfactwithdetails factdetails = (reports.reportfactwithdetails)results.getfactmap().get(factmapkey); // get the first summary amount from the fact map reports.summaryvalue sumval = factdetails.getaggregates()[0]; system.debug('summary value: ' + sumval.getlabel()); // get the field value from the first data cell of the first row of the report reports.reportdetailrow detailrow = factdetails.getrows()[0]; system.debug(detailrow.getdatacells()[0].getlabel()); filter reports to get specific results on the fly, you can filter reports through the api. changes to filters that are made through the api don’t affect the source report definition. using the api, you can filter with up to 20 custom field filters and add filter logic (such as and and or). but standard filters (such as range), filtering by
row limit, and cross filters are unavailable. before you filter a report, it’s helpful to check the following filter values in the metadata. • the reporttypecolumn.getfilterable method tells you whether a field can be filtered. • the reporttypecolumn.filtervalues method returns all filter values for a field. • the reportmanager.datatypefilteroperatormap method lists the field data types that you can use to filter the report. • the reportmetadata.getreportfilters method lists all filters that exist in the report. you can filter reports during synchronous or asynchronous report runs. example: to filter a report, set filter values in the report metadata and then run the report. the following example retrieves the report metadata, overrides the filter value, and runs the report. the example: 1. retrieves the report filter object from the metadata by using the reportmetadata.getreportfilters method. 512apex developer guide using salesforce features with apex 2. sets the value in the filter to a specific date by using the reportfilter.setvalue method and runs the report. 3. overrides the filter value to a different date and runs the report again. the output for the example shows the differing grand total values, based on the date filter that was applied. // get the report id list <report> reportlist = [select id,developername from report where developername = 'closed_sales_this_quarter']; string reportid = (string)reportlist.get(0).get('id'); // get the report metadata reports.reportdescriberesult describe = reports.reportmanager.describereport(reportid); reports.reportmetadata reportmd = describe.getreportmetadata(); // override filter and run report reports.reportfilter filter = reportmd.getreportfilters()[0]; filter.setvalue('2013-11-01'); reports.reportresults results = reports.reportmanager.runreport(reportid, reportmd); reports.reportfactwithsummaries factsum = (reports.reportfactwithsummaries)results.getfactmap().get('t!t'); system.debug('value for november: ' + factsum.getaggregates()[0].getlabel()); // override filter and run report filter = reportmd.getreportfilters()[0]; filter.setvalue('2013-10-01'); results = reports.reportmanager.runreport(reportid, reportmd); factsum = (reports.reportfactwithsummaries)results.getfactmap().get('t!t'); system.debug('value for october: ' + factsum.getaggregates()[0].getlabel()); decode the fact map the fact map contains the summary and record-level data values for a report. depending on how you run a report, the fact map in the report results can contain values for only summary or both summary and detailed data. the fact map values are expressed as keys, which you can programmatically use to visualize the report data. fact map keys provide an index into each section of a fact map, from which you can access summary and detailed data. the pattern for the fact map keys varies by report format as shown in this table. report fact map key pattern format tabular t!t: the grand total of a report. both record data values and the grand total are represented by this key. summary <first level row grouping_second level row grouping_third level row grouping>!t: t refers to the row grand total. matrix <first level row grouping_second level row grouping>!<first level column grouping_second level column grouping>. each item in a row or column grouping is numbered starting with 0. here are some examples of fact map keys: 513apex developer guide using salesforce features with apex fact map description key 0!t the first item in the first-level grouping. 1!t the second item in the first-level grouping. 0_0!t the first item in the first-level grouping and the first item in the second-level grouping. 0_1!t the first item in the first-level grouping and the second item in the second-level grouping. let’s look at examples of how fact map keys represent data as it appears in a salesforce tabular, summary, or matrix report. tabular report fact map here’s an example of an opportunities report in tabular format. since tabular reports don’t have groupings, all of the record level data and summaries are expressed
by the t!t key, which refers to the grand total. summary report fact map this example shows how the values in a summary report are represented in the fact map. 514apex developer guide using salesforce features with apex fact map key description 0!t summary for the value of opportunities in the prospecting stage. 1_0!t summary of the probabilities for the manufacturing opportunities in the needs analysis stage. matrix report fact map here’s an example of some fact map keys for data in a matrix opportunities report with a couple of row and column groupings. fact map key description 0!0 total opportunity amount in the prospecting stage in q4 2010. 0_0!0_0 total opportunity amount in the prospecting stage in the manufacturing sector in october 2010. 2_1!1_1 total value of opportunities in the value proposition stage in the technology sector in february 2011. t!t grand total summary for the report. test reports like all apex code, salesforce reports and dashboards api via apex code requires test coverage. the reporting apex methods don’t run in system mode, they run in the context of the current user (also called the context user or the logged-in user). the methods have access to whatever the current user has access to. 515apex developer guide using salesforce features with apex in apex tests, report runs always ignore the seealldata annotation, regardless of whether the annotation is set to true or false. this means that report results will include pre-existing data that the test didn’t create. there is no way to disable the seealldata annotation for a report execution. to limit results, use a filter on the report. example: create a reports test class the following example tests asynchronous and synchronous reports. each method: • creates a new opportunity object and uses it to set a filter on the report. • runs the report. • calls assertions to validate the data. note: in apex tests, asynchronous reports execute only after the test is stopped using the test.stoptest method. @istest public class reportsinapextest{ @istest(seealldata='true') public static void testasyncreportwithtestdata() { list <report> reportlist = [select id,developername from report where developername = 'closed_sales_this_quarter']; string reportid = (string)reportlist.get(0).get('id'); // create an opportunity object. opportunity opp = new opportunity(name='apextestopp', stagename='stage', probability = 95, closedate=system.today()); insert opp; reports.reportmetadata reportmetadata = reports.reportmanager.describereport(reportid).getreportmetadata(); // add a filter. list<reports.reportfilter> filters = new list<reports.reportfilter>(); reports.reportfilter newfilter = new reports.reportfilter(); newfilter.setcolumn('opportunity_name'); newfilter.setoperator('equals'); newfilter.setvalue('apextestopp'); filters.add(newfilter); reportmetadata.setreportfilters(filters); test.starttest(); reports.reportinstance instanceobj = reports.reportmanager.runasyncreport(reportid,reportmetadata,false); string instanceid = instanceobj.getid(); // report instance is not available yet. test.stoptest(); // after the stoptest method, the report has finished executing // and the instance is available. instanceobj = reports.reportmanager.getreportinstance(instanceid); system.assertequals(instanceobj.getstatus(),'success'); reports.reportresults result = instanceobj.getreportresults(); 516apex developer guide using salesforce features with apex reports.reportfact grandtotal = (reports.reportfact)result.getfactmap().get('t!t'); system.assertequals(1,(decimal)grandtotal.getaggregates().get(1).getvalue()); } @istest(seealldata='true') public static void testsyncreportwithtestdata() { // create an opportunity object. opportunity opp = new opportunity(name='apextestopp', stagename='stage', probability = 95, closedate=system.today()); insert opp; list <report> reportlist = [select id,developername from report where developername = 'closed_sales_this_quarter']; string reportid = (string)reportlist.get(0).get('id
'); reports.reportmetadata reportmetadata = reports.reportmanager.describereport(reportid).getreportmetadata(); // add a filter. list<reports.reportfilter> filters = new list<reports.reportfilter>(); reports.reportfilter newfilter = new reports.reportfilter(); newfilter.setcolumn('opportunity_name'); newfilter.setoperator('equals'); newfilter.setvalue('apextestopp'); filters.add(newfilter); reportmetadata.setreportfilters(filters); reports.reportresults result = reports.reportmanager.runreport(reportid,reportmetadata,false); reports.reportfact grandtotal = (reports.reportfact)result.getfactmap().get('t!t'); system.assertequals(1,(decimal)grandtotal.getaggregates().get(1).getvalue()); } } salesforce sites salesforce sites lets you build custom pages and web applications by inheriting lightning platform capabilities including analytics, workflow and approvals, and programmable logic. you can manage your salesforce sites in apex using the methods of the site and cookie classes. 517apex developer guide using salesforce features with apex in this section: rewrite urls for salesforce sites sites provides built-in logic that helps you display user-friendly urls and links to site visitors. create rules to rewrite url requests typed into the address bar, launched from bookmarks, or linked from external websites. you can also create rules to rewrite the urls for links within site pages. url rewriting not only makes urls more descriptive and intuitive for users, it allows search engines to better index your site pages. see also: apex reference guide: site class rewrite urls for salesforce sites sites provides built-in logic that helps you display user-friendly urls and links to site visitors. create rules to rewrite url requests typed into the address bar, launched from bookmarks, or linked from external websites. you can also create rules to rewrite the urls for links within site pages. url rewriting not only makes urls more descriptive and intuitive for users, it allows search engines to better index your site pages. for example, let's say that you have a blog site. without url rewriting, a blog entry's url might look like this: https://myblog.my.salesforce-sites.com/posts?id=003d000000q0pcn with url rewriting, your users can access blog posts by date and title, say, instead of by record id. the url for one of your new year's eve posts might be: https://myblog.my.salesforce-sites.com/posts/2019/12/31/auld-lang-syne you can also rewrite urls for links shown within a site page. if your new year's eve post contained a link to your valentine's day post, the link url might show: https://myblog.my.salesforce-sites.com/posts/2019/02/14/last-minute-roses to rewrite urls for a site, create an apex class that maps the original urls to user-friendly urls, and then add the apex class to your site. to learn about the methods in the site.urlrewriter interface, see urlrewriter interface. creating the apex class the apex class that you create must implement the provided interface site.urlrewriter. in general, it must have the following form: global class yourclass implements site.urlrewriter { global pagereference maprequesturl(pagereference yourfriendlyurl) global pagereference[] generateurlfor(pagereference[] yoursalesforceurls); } consider the following restrictions and recommendations as you create your apex class: class and methods must be global the apex class and methods must all be global. class must include both methods the apex class must implement both the maprequesturl and generateurlfor methods. if you don't want to use one of the methods, simply have it return null. rewriting only works for visualforce site pages incoming url requests can only be mapped to visualforce pages associated with your site. you can't map to standard pages, images, or other entities. 518apex developer guide using salesforce features with apex to rewrite urls for links on your site's pages, use the !urlfor function with the $page merge variable. for example, the following links to a visualforce page named mypage: <apex:outputlink value="{!urlfor($page.mypage)}"></apex:outputlink> note: visualforce <apex
:form> elements with forcessl=”true” aren't affected by the urlrewriter. see the “functions” appendix of the visualforce developer's guide. encoded urls the urls you get from using the site.urlrewriter interface are encoded. if you need to access the unencoded values of your url, use the urldecode method of the encodingutil class. restricted characters user-friendly urls must be distinct from salesforce urls. urls with a 3-character entity prefix or a 15- or 18-character id aren’t rewritten. you can’t use periods in your user-friendly or rewritten urls, except for the .well-known path component, which can’t be used at the end of a url. restricted strings you can’t use the following reserved strings as the first path component after a site’s base url in either a user-friendly url or a rewritten url. some examples of the first past component after a site’s base url are baseurl in https://mydomainname.my.salesforce-sites.com/baseurl, https://mydomainname.my.salesforce-sites.com/pathprefix/baseurl, https://custom-domain/pathprefix/baseurl, and https://mydomainname.my.salesforce-sites.com/pathprefix/baseurl/another/path. • apexcomponent • apexpages • aura • chatter • chatteranswers • chatterservice • cometd • ex • faces • flash • flex • google • home • id • ideas • idp • images • img • javascript • js • knowledge • lightning 519apex developer guide using salesforce features with apex • login • m • mobile • ncsphoto • nui • push • resource • saml • sccommunities • search • secur • services • servlet • setup • sfc • sfdc • sfdc_ns • sfsites • site • style • vote • web-inf • widg you can't use the following reserved strings at the end of a rewritten url path: • /aura • /aurafw • /auraresource • /aurajloggingrpcservice • /aurajlvrpcservice • /aurajrpcservice • /dbcthumbnail • /helpandtrainingdoor • /htmldbcthumbnail • /l • /m • /mobile relative paths only the pagereference.geturl() method only returns the part of the url immediately following the host name or site prefix (if any). for example, if your url is https://mycompany.my.salesforce-sites.com/sales/mypage?id=12345, where “sales” is the site prefix, only /mypage?id=12345 is returned. 520apex developer guide using salesforce features with apex you can't rewrite the domain or site prefix. unique paths only you can't map a url to a directory that has the same name as your site prefix. for example, if your site url is https://acme.my.salesforce-sites.com/help, where “help” is the site prefix, you can't point the url to help/page. the resulting path, https://acme.my.salesforce-sites.com/help/help/page, would be returned instead as https://acme.my.salesforce-sites.com/help/page. query in bulk for better performance with page generation, perform tasks in bulk rather than one at a time for the generateurlfor method. enforce field uniqueness make sure the fields you choose for rewriting urls are unique. using unique or indexed fields in soql for your queries may improve performance. adding url rewriting to a site once you've created the url rewriting apex class, follow these steps to add it to your site: 1. from setup, enter sites in the quick find box, then select sites. 2. click new or click edit for an existing site. 3. on the site edit page, choose an apex class for url rewriter class. 4. click save. note: if you have url rewriting enabled on your site, all pagereferences are passed through the url rewriter. pagereferences with redirect set to true and
a redirectcode other than 0 return redirected urls instead of rewritten urls. code example in this example, we have a simple site consisting of two visualforce pages: mycontact and myaccount. be sure you have “read” permission enabled for both before trying the sample. each page uses the standard controller for its object type. the contact page includes a link to the parent account, plus contact details. before implementing rewriting, the address bar and link urls showed the record id (a random 15-digit string), illustrated in the “before” figure. once rewriting was enabled, the address bar and links show more user-friendly rewritten urls, illustrated in the “after” figure. the apex class used to rewrite the urls for these pages is shown in example url rewriting apex class, with detailed comments. example site pages this section shows the visualforce for the account and contact pages used in this example. the account page uses the standard controller for accounts and is nothing more than a standard detail page. this page should be named myaccount. <apex:page standardcontroller="account"> <apex:detail relatedlist="false"/> </apex:page> the contact page uses the standard controller for contacts and consists of two parts. the first part links to the parent account using the urlfor function and the $page merge variable; the second simply provides the contact details. notice that the visualforce page doesn't contain any rewriting logic except urlfor. this page should be named mycontact. <apex:page standardcontroller="contact"> <apex:pageblock title="parent account"> 521apex developer guide using salesforce features with apex <apex:outputlink value="{!urlfor($page.mycontact,null, [id=contact.account.id])}">{!contact.account.name} </apex:outputlink> </apex:pageblock> <apex:detail relatedlist="false"/> </apex:page> example url rewriting apex class the apex class used as the url rewriter for the site uses the maprequesturl method to map incoming url requests to the right salesforce record. it also uses the generateurlfor method to rewrite the url for the link to the account page in a more user-friendly form. global with sharing class myrewriter implements site.urlrewriter { //variables to represent the user-friendly urls for //account and contact pages string account_page = '/myaccount/'; string contact_page = '/mycontact/'; //variables to represent my custom visualforce pages //that display account and contact information string account_visualforce_page = '/myaccount?id='; string contact_visualforce_page = '/mycontact?id='; global pagereference maprequesturl(pagereference myfriendlyurl){ string url = myfriendlyurl.geturl(); if(url.startswith(contact_page)){ //extract the name of the contact from the url //for example: /mycontact/ryan returns ryan string name = url.substring(contact_page.length(), url.length()); //select the id of the contact that matches //the name from the url contact con = [select id from contact where name =: name limit 1]; //construct a new page reference in the form //of my visualforce page return new pagereference(contact_visualforce_page + con.id); } if(url.startswith(account_page)){ //extract the name of the account string name = url.substring(account_page.length(), url.length()); //query for the id of an account with this name account acc = [select id from account where name =:name limit 1]; //return a page in visualforce format return new pagereference(account_visualforce_page + acc.id); } 522apex developer guide using salesforce features with apex //if the url isn't in the form of a contact or //account page, continue with the request return null; } global list<pagereference> generateurlfor(list<pagereference> mysalesforceurls){ //a list of pages to return after all the links //have been evaluated list<pagereference> myfriendlyurls = new list<pagereference>(); //a list of all the ids in the urls list<id> accids = new list<id>
(); // loop through all the urls once, finding all the valid ids for(pagereference mysalesforceurl : mysalesforceurls){ //get the url of the page string url = mysalesforceurl.geturl(); //if this looks like an account page, transform it if(url.startswith(account_visualforce_page)){ //extract the id from the query parameter //and store in a list //for querying later in bulk. string id= url.substring(account_visualforce_page.length(), url.length()); accids.add(id); } } // get all the account names in bulk list <account> accounts = [select name from account where id in :accids]; // make the new urls integer counter = 0; // it is important to go through all the urls again, so that the order // of the urls in the list is maintained. for(pagereference mysalesforceurl : mysalesforceurls) { //get the url of the page string url = mysalesforceurl.geturl(); if(url.startswith(account_visualforce_page)){ myfriendlyurls.add(new pagereference(account_page + accounts.get(counter).name)); counter++; } else { //if this doesn't start like an account page, //don't do any transformations myfriendlyurls.add(mysalesforceurl); } } //return the full list of pages 523apex developer guide using salesforce features with apex return myfriendlyurls; } } before and after rewriting here is a visual example of the results of implementing the apex class to rewrite the original site urls. notice the id-based urls in the first figure, and the user-friendly urls in the second. site urls before rewriting the numbered elements in this figure are: 1. the original url for the contact page before rewriting 2. the link to the parent account page from the contact page 3. the original url for the link to the account page before rewriting, shown in the browser's status bar 524apex developer guide using salesforce features with apex site urls after rewriting the numbered elements in this figure are: 1. the rewritten url for the contact page after rewriting 2. the link to the parent account page from the contact page 3. the rewritten url for the link to the account page after rewriting, shown in the browser's status bar support classes support classes allow you to interact with records commonly used by support centers, such as business hours and cases. working with business hours business hours are used to specify the hours at which your customer support team operates, including multiple business hours in multiple time zones. this example finds the time one business hour from starttime, returning the datetime in the local time zone. it gets the default business hours by querying businesshours. also, it calls the businesshours add method. // get the default business hours businesshours bh = [select id from businesshours where isdefault=true]; // create datetime on may 28, 2008 at 1:06:08 am in local timezone. datetime starttime = datetime.newinstance(2008, 5, 28, 1, 6, 8); // find the time it will be one business hour from may 28, 2008, 1:06:08 am using the // default business hours. the returned datetime will be in the local timezone. datetime nexttime = businesshours.add(bh.id, starttime, 60 * 60 * 1000l); this example finds the time one business hour from starttime, returning the datetime in gmt: // get the default business hours businesshours bh = [select id from businesshours where isdefault=true]; 525apex developer guide using salesforce features with apex // create datetime on may 28, 2008 at 1:06:08 am in local timezone. datetime starttime = datetime.newinstance(2008, 5, 28, 1, 6, 8); // find the time it will be one business hour from may 28, 2008, 1:06:08 am using the // default business hours. the returned datetime will be in gmt. datetime nexttimegmt = businesshours.addgmt(bh.id, starttime, 60 * 60 * 1000l); the next example finds the difference between starttime and nexttime: // get the default business hours businesshours bh = [select id from businesshours
where isdefault=true]; // create datetime on may 28, 2008 at 1:06:08 am in local timezone. datetime starttime = datetime.newinstance(2008, 5, 28, 1, 6, 8); // create datetime on may 28, 2008 at 4:06:08 pm in local timezone. datetime endtime = datetime.newinstance(2008, 5, 28, 16, 6, 8); // find the number of business hours milliseconds between starttime and endtime as // defined by the default business hours. will return a negative value if endtime is // before starttime, 0 if equal, positive value otherwise. long diff = businesshours.diff(bh.id, starttime, endtime); working with cases incoming and outgoing email messages can be associated with their corresponding cases using the cases class getcaseidfromemailthreadid method. this method is used with email-to-case, which is an automated process that turns emails received from customers into customer service cases. the following example uses an email thread id to retrieve the related case id. public class getcaseidcontroller { public static void getcaseidsample() { // get email thread id string emailthreadid = '_00dxx1gew._500xxyktg'; // call apex method to retrieve case id from email thread id id caseid = cases.getcaseidfromemailthreadid(emailthreadid); } } see also: apex reference guide: businesshours class apex reference guide: cases class territory management 2.0 with trigger support for the territory2 and userterritory2association standard objects, you can automate actions and processes related to changes in these territory management records. 526apex developer guide using salesforce features with apex sample trigger for territory2 this example trigger fires after territory2 records have been created or deleted. this example trigger assumes that an organization has a custom field called territorycount__c defined on the territory2model object to track the net number of territories in each territory model. the trigger code increments or decrements the value in the territorycount__c field each time a territory is created or deleted. trigger maintainterritorycount on territory2 (after insert, after delete) { // track the effective delta for each model map<id, integer> modelmap = new map<id, integer>(); for(territory2 terr : (trigger.isinsert ? trigger.new : trigger.old)) { integer offset = 0; if(modelmap.containskey(terr.territory2modelid)) { offset = modelmap.get(terr.territory2modelid); } offset += (trigger.isinsert ? 1 : -1); modelmap.put(terr.territory2modelid, offset); } // we have a custom field on territory2model called territorycount__c list<territory2model> models = [select id, territorycount__c from territory2model where id in :modelmap.keyset()]; for(territory2model tm : models) { // in case the field is not defined with a default of 0 if(tm.territorycount__c == null) { tm.territorycount__c = 0; } tm.territorycount__c += modelmap.get(tm.id); } // bulk update the field on all the impacted models update(models); } sample trigger for userterritory2association this example trigger fires after userterritory2association records have been created. this example trigger sends an email notification to the sales operations group letting them know that users have been added to territories. it identifies the user who added users to territories. then, it identifies each added user along with which territory the user was added to and which territory model the territory belongs to. trigger notifysalesops on userterritory2association (after insert) { // query the details of the users and territories involved list<userterritory2association> utalist = [select id, user.firstname, user.lastname, territory2.name, territory2.territory2model.name from userterritory2association where id in :trigger.new]; // email message to send messaging.singleemailmessage mail = new messaging.singleemailmessage(); mail.settoaddresses(new string[]{'[email protected]'}); mail.setsubject('users
added to territories notification'); // build the message body list<string> msgbody = new list<string>(); string addedtoterrstr = '{0}, {1} added to territory {2} in model {3} \n'; 527apex developer guide integration and apex utilities msgbody.add('the following users were added to territories by ' + userinfo.getfirstname() + ', ' + userinfo.getlastname() + '\n'); for(userterritory2association uta : utalist) { msgbody.add(string.format(addedtoterrstr, new string[]{uta.user.firstname, uta.user.lastname, uta.territory2.name, uta.territory2.territory2model.name})); } // set the message body and send the email mail.setplaintextbody(string.join(msgbody,'')); messaging.sendemail(new messaging.email[] { mail }); } integration and apex utilities apex allows you to integrate with external soap and rest web services using callouts. you can use utilities for json, xml, data security, and encoding. a general-purpose utility for regular expressions with text strings is also provided. in this section: invoking callouts using apex json support javascript object notation (json) support in apex enables the serialization of apex objects into json format and the deserialization of serialized json content. xml support apex provides utility classes that enable the creation and parsing of xml content using streams and the dom. securing your data you can secure your data by using the methods provided by the crypto class. encoding your data you can encode and decode urls and convert strings to hexadecimal format by using the methods provided by the encodingutil class. using patterns and matchers apex provides patterns and matchers that enable you to search text using regular expressions. invoking callouts using apex an apex callout enables you to tightly integrate your apex with an external service by making a call to an external web service or sending a http request from apex code and then receiving the response. apex provides integration with web services that utilize soap and wsdl, or http services (restful services). note: before any apex callout can call an external site, that site must be registered in the remote site settings page, or the callout fails. salesforce prevents calls to unauthorized network addresses. if the callout specifies a named credential as the endpoint, you don’t need to configure remote site settings. a named credential specifies the url of a callout endpoint and its required authentication parameters in one definition. to set up named credentials, see “define a named credential” in the salesforce help. to learn more about the types of callouts, see: 528apex developer guide integration and apex utilities • soap services: defining a class from a wsdl document on page 534 • invoking http callouts on page 546 • asynchronous callouts for long-running requests on page 558 tip: callouts enable apex to invoke external web or http services. apex web services allow an external application to invoke apex methods through web services. in this section: 1. adding remote site settings 2. named credentials as callout endpoints 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. you can also skip remote site settings, which are otherwise required for callouts to external sites, for the site defined in the named credential. 3. soap services: defining a class from a wsdl document 4. invoking http callouts 5. using certificates 6. callout limits and limitations 7. make long-running callouts with continuations use asynchronous callouts to make long-running requests from a visualforce page or a lightning component to an external web service and process responses in callback methods. adding remote site settings before any apex callout can call an external site, that site must be registered in the remote site settings page, or the callout fails. salesforce prevents calls to unauthorized network addresses. note: if the callout specifies a named credential as the endpoint, you don’t need to configure remote site settings. a named credential specifies the url of a callout endpoint and its required authentication parameters in