### Insert Trigger Examples Source: https://github.com/trailheadapps/apex-recipes/wiki/AccountTriggerHandler Examples demonstrating account insertion in trigger contexts. ```apex Account[] accounts = new Account[](); accounts.add(new Account(name='example 1')); accounts.add(new Account(name='example 2')); insert accounts; ``` -------------------------------- ### Create External Credential Example Source: https://github.com/trailheadapps/apex-recipes/blob/main/force-app/main/default/staticresources/documentation/NamedCredentialRecipes.md Usage example for creating an external credential. ```apex System.debug(NamedCredentialRecipes.createExternalCredential(new ConnectApiWrapper(), 'Apex_Recipes')); ``` -------------------------------- ### Update Trigger Examples Source: https://github.com/trailheadapps/apex-recipes/wiki/AccountTriggerHandler Examples demonstrating account updates in trigger contexts. ```apex Account[] accounts = new Account[](); accounts.add(new Account(name='example 1')); accounts.add(new Account(name='example 2')); insert accounts; accounts[0].name += ' Updated'; update accounts; ``` -------------------------------- ### Delete Trigger Examples Source: https://github.com/trailheadapps/apex-recipes/wiki/AccountTriggerHandler Examples demonstrating account deletion in trigger contexts. ```apex Account[] accounts = new Account[](); accounts.add(new Account(name='example 1')); insert accounts; delete accounts; ``` -------------------------------- ### Execute Setup Script Source: https://github.com/trailheadapps/apex-recipes/blob/main/README.md Runs the anonymous Apex script to configure the environment. ```bash sf apex run --file data/setup.apex ``` -------------------------------- ### Create Named Credential Example Source: https://github.com/trailheadapps/apex-recipes/blob/main/force-app/main/default/staticresources/documentation/NamedCredentialRecipes.md Usage example for creating a named credential and performing a subsequent API call. ```apex System.debug(NamedCredentialRecipes.createNamedCredential(new ConnectApiWrapper(), 'Apex_Recipes')); HttpResponse response = RestClient.makeApiCall( NAMED_CREDENTIAL_DEVELOPER_NAME, RestClient.HttpVerb.GET, '/volumes?q=salesforce' ); System.debug(response.getBody()); ``` -------------------------------- ### Initialize LDVRecipes constructor Source: https://github.com/trailheadapps/apex-recipes/wiki/LDVRecipes Constructor for starting the queueable chain. ```apex public LDVRecipes() ``` -------------------------------- ### Execute raw HTTP GET callout in Apex Source: https://github.com/trailheadapps/apex-recipes/wiki/CalloutRecipes Demonstrates the use of standard Http, HttpRequest, and HttpResponse objects for a basic GET request. ```apex System.debug(CalloutRecipes.rawCallout()); ``` -------------------------------- ### Convenience get method Source: https://github.com/trailheadapps/apex-recipes/wiki/IterableApiClient Simplified method for performing a GET request using only a path. ```apex protected HttpResponse get(String path) ``` -------------------------------- ### Perform GET request Source: https://github.com/trailheadapps/apex-recipes/blob/main/force-app/main/default/staticresources/documentation/IterableApiClient.md Executes a GET call using a path and query string. ```apex protected HttpResponse get(String path, String query) ``` -------------------------------- ### GET Request Methods Source: https://github.com/trailheadapps/apex-recipes/wiki/ApiServiceRecipes Convenience methods for performing GET requests with optional query parameters. ```apex protected HttpResponse get(String path) ``` ```apex protected HttpResponse get(String path, String query) ``` -------------------------------- ### Schedule Apex Job Source: https://github.com/trailheadapps/apex-recipes/wiki/ScheduledApexRecipes Example of how to programmatically schedule an instance of the class using a cron expression. ```apex System.schedule('Friendly Message to identify this job', ScheduledApexRecipes.TEST_CRON_STATEMENT, new ScheduledApexRecipes()); ``` -------------------------------- ### rawCallout() Source: https://github.com/trailheadapps/apex-recipes/wiki/CalloutRecipes Demonstrates a manual, raw HTTP GET request using standard Apex Http classes. ```APIDOC ## Method: rawCallout() ### Description Demonstrates how to make a raw HTTP GET request using the Http, HttpRequest, and HttpResponse objects. ### Return Type - **String** - The response body as a string. ``` -------------------------------- ### Generate Tree Data Example Source: https://github.com/trailheadapps/apex-recipes/wiki/RecipeTreeViewController Displays the output of the generateTreeData method in the debug log. ```apex System.debug(RecipeTreeViewController.generateTreeData()); ``` -------------------------------- ### Get greeting method Source: https://github.com/trailheadapps/apex-recipes/wiki/StubExample Returns the string value of the greeting field. ```apex public String getGreeting() ``` -------------------------------- ### Enqueue QueueableWithCalloutRecipes Job Source: https://github.com/trailheadapps/apex-recipes/wiki/QueueableWithCalloutRecipes Example of how to trigger the asynchronous job execution. ```apex System.enqueueJob(new QueueableWithCalloutRecipes()); ``` -------------------------------- ### Execute runAtMidnight method Source: https://github.com/trailheadapps/apex-recipes/wiki/ScheduledApexDemo Example of invoking the runAtMidnight method from the ScheduledApexDemo class. ```apex ScheduledApexDemo.runAtMidnight(); ``` -------------------------------- ### GET /services/apexrest/integration-service Source: https://github.com/trailheadapps/apex-recipes/wiki/CustomRestEndpointRecipes Retrieves a list of Accounts from Salesforce. ```APIDOC ## GET /services/apexrest/integration-service ### Description Queries a list of Accounts created in Salesforce and returns them as a JSON string. ### Method GET ### Endpoint /services/apexrest/integration-service ### Response #### Success Response (200) - **body** (String) - JSON string holding the list of Accounts. ### Request Example curl -H "Authorization: Bearer " "https:///services/apexrest/integration-service" ``` -------------------------------- ### Import Sample Data Source: https://github.com/trailheadapps/apex-recipes/blob/main/README.md Populates the scratch org with sample data using defined data plans. ```bash sf data tree import -p ./data/data-plan.json sf data tree import -p ./data/data-plan2.json ``` -------------------------------- ### Retrieve cached data using CacheBuilder Source: https://github.com/trailheadapps/apex-recipes/wiki/PlatformCacheBuilderRecipes Example of retrieving data from the cache using the Cache.Session.get method with a CacheBuilder implementation. ```apex Account[] accounts = (Account[]) Cache.Session.get(PlatformCacheBuilderRecipes.class, 'myAccounts') ``` -------------------------------- ### Create Scratch Org Source: https://github.com/trailheadapps/apex-recipes/blob/main/README.md Initializes a new scratch org based on the project configuration file. ```bash sf org create scratch -d -f config/project-scratch-def.json -a apex-recipes ``` -------------------------------- ### Open Scratch Org Source: https://github.com/trailheadapps/apex-recipes/blob/main/README.md Launches the scratch org in the default web browser. ```bash sf org open ``` -------------------------------- ### Deploy Project Source: https://github.com/trailheadapps/apex-recipes/blob/main/README.md Deploys the application source code to the active scratch org. ```bash sf project deploy start ``` -------------------------------- ### Open Salesforce Org Source: https://github.com/trailheadapps/apex-recipes/blob/main/README.md Launch the authorized org in your default web browser. ```bash sf org open -o mydevorg ``` -------------------------------- ### Publishing a Platform Event Source: https://github.com/trailheadapps/apex-recipes/wiki/PlatformEventRecipesTriggerHandler Demonstrates creating an account and publishing a platform event to trigger the handler logic. ```apex Account acct = new Account(Name = 'Awesome Events Ltd.'); insert acct; Event_Recipes_Demo__e evt = new Event_Recipes_Demo__e(AccountId__c = acct.id, Title__c='Updated website', Url__c = 'https://developer.salesforce.com'); Database.saveResults result = PlatformEventsRecipes.publishEvent(evt); System.debug(result + [SELECT Name, Website FROM Account WHERE Id = :acct.id]); ``` -------------------------------- ### Usage of TestDouble for Stubbing Source: https://github.com/trailheadapps/apex-recipes/wiki/TestDouble Demonstrates the initialization of a TestDouble, tracking a method, and generating the stub for dependency injection. ```apex TestDouble stub = new TestDouble(SomeClass.class); TestDouble.Method methodToTrack = new TestDouble.Method('methodName') .returning(someObject); stub.track(methodToTrack); ConsumingClass consumer = new ConsumingClass( (someClass) stub.generate() ); ``` -------------------------------- ### Get isTrue method Source: https://github.com/trailheadapps/apex-recipes/wiki/StubExample Returns the boolean value of the isTrue field. ```apex public Boolean getIsTrue() ``` -------------------------------- ### Deploy Project Metadata Source: https://github.com/trailheadapps/apex-recipes/blob/main/README.md Push the application source code to the authorized Salesforce org. ```bash sf project deploy start -d force-app ``` -------------------------------- ### Execute method signature for OrderAppMenu Source: https://github.com/trailheadapps/apex-recipes/wiki/OrderAppMenu Defines the entry point for the Queueable job to reorder the App Menu. ```apex public void execute(QueueableContext qc) ``` -------------------------------- ### Get current loop count Source: https://github.com/trailheadapps/apex-recipes/blob/main/force-app/main/default/staticresources/documentation/TriggerHandler.md Retrieves the current value of the loop counter. ```apex public getCount() ``` -------------------------------- ### Get maximum loop count Source: https://github.com/trailheadapps/apex-recipes/blob/main/force-app/main/default/staticresources/documentation/TriggerHandler.md Retrieves the configured maximum loop count. ```apex public Integer getMax() ``` -------------------------------- ### Clone Repository Source: https://github.com/trailheadapps/apex-recipes/blob/main/README.md Downloads the Apex Recipes source code and navigates into the directory. ```bash git clone https://github.com/trailheadapps/apex-recipes cd apex-recipes ``` -------------------------------- ### Define ExampleObject fields Source: https://github.com/trailheadapps/apex-recipes/blob/main/force-app/main/default/staticresources/documentation/ApiServiceRecipesDataModel.md Fields for the nested ExampleObject class. ```apex public a ``` ```apex public c ``` -------------------------------- ### Get Default Partition Source: https://github.com/trailheadapps/apex-recipes/wiki/PlatformCacheRecipes Returns a Cache.Partition object for a given partition type. ```apex public static Cache.Partition getDefaultPartition(PartitionType type) ``` -------------------------------- ### Query Accounts with getRecords Source: https://github.com/trailheadapps/apex-recipes/wiki/SOQLRecipes Demonstrates querying Account records while adhering to FLS and CRUD security best practices. ```apex List results = SOQLRecipes.querySingleObject(); System.debug(results); ``` -------------------------------- ### StubExampleConsumer(StubExample stub) Source: https://github.com/trailheadapps/apex-recipes/wiki/StubExampleConsumer Constructor to initialize the consumer with a StubExample instance. ```APIDOC ### Constructor `public StubExampleConsumer(StubExample stub)` #### Parameters - **stub** (StubExample) - Required - The stub instance to be consumed. ``` -------------------------------- ### Get Handler Name Method Source: https://github.com/trailheadapps/apex-recipes/wiki/TriggerHandler Returns the string representation of the current handler class. ```apex private String getHandlerName() ``` -------------------------------- ### httpGetCalloutToSecondOrg() Source: https://github.com/trailheadapps/apex-recipes/wiki/CalloutRecipes Performs a GET request to retrieve a list of Accounts from a second Salesforce organization. ```APIDOC ## Method: httpGetCalloutToSecondOrg() ### Description Retrieves a list of Accounts from a target endpoint using the RestClient abstraction. ### Return Type - **List** - A list of Account records retrieved from the target org. ``` -------------------------------- ### basicSOSLSearch() Source: https://github.com/trailheadapps/apex-recipes/wiki/SOSLRecipes Demonstrates the basic syntax for a SOSL search. Note that SOSL cannot be unit tested directly and requires the use of Test.setFixedSearchResults(). ```APIDOC ## basicSOSLSearch() ### Description Demonstrates the syntax for a SOSL search. ### Signature `public static List> basicSOSLSearch()` ### Return Type List> ### Example ```apex System.debug(SOSLRecipes.basicSOSLSearch()); ``` ``` -------------------------------- ### Define exampleString field Source: https://github.com/trailheadapps/apex-recipes/wiki/ApiServiceRecipesDataModel Represents a string property for JSON serialization. ```apex public exampleString ``` -------------------------------- ### Get SObject Type Source: https://github.com/trailheadapps/apex-recipes/wiki/MetadataTriggerService Determines the active sObject type by describing the first record in the trigger context. ```apex public static String getSObjectType() ``` -------------------------------- ### Run Linting and Formatting Commands Source: https://github.com/trailheadapps/apex-recipes/blob/main/README.md Manual commands to execute ESLint and Prettier formatting checks from the command line. ```bash npm run lint npm run prettier ``` -------------------------------- ### Get SObject Type from List Source: https://github.com/trailheadapps/apex-recipes/wiki/CollectionUtils Internal helper method to determine the SObject type from a provided list. ```apex private static String getSobjectTypeFromList(List incomingList) ``` -------------------------------- ### Define ExampleObject field c Source: https://github.com/trailheadapps/apex-recipes/wiki/ApiServiceRecipesDataModel Represents a string field within the nested ExampleObject class. ```apex public c ``` -------------------------------- ### Get External Credential Method Signature Source: https://github.com/trailheadapps/apex-recipes/wiki/ConnectApiWrapper Defines the signature for retrieving an external credential by its developer name. ```apex public ConnectApi.ExternalCredential getExternalCredential(String developerName) ``` -------------------------------- ### Make API Call with Full Parameters Source: https://github.com/trailheadapps/apex-recipes/wiki/ApiServiceRecipes Static wrapper for executing HTTP requests with explicit headers and body. ```apex public static HttpResponse makeApiCall(String namedCredential, HttpVerb method, String path, String query, String body, Map headers) ``` ```apex System.Debug(RestClient.makeApiCall('GoogleBooksAPI', RestClient.HttpVerb.GET, 'volumes', 'q=salesforce', '', new Map())); ``` -------------------------------- ### Decrypt and Verify Signature Usage Source: https://github.com/trailheadapps/apex-recipes/wiki/EncryptionRecipes Example usage of the decryption and signature verification method within a try-catch block. ```apex try { EncryptionRecipes.decryptAES256AndCheckRSASHA512DigitalSignRecipe(signature, corruptedData); } catch(Exception e) { // Should log exception System.debug(e.getMessage()); } ``` -------------------------------- ### JSON Payload for Account Update Source: https://github.com/trailheadapps/apex-recipes/wiki/CustomRestEndpointRecipes Example JSON structure used as a request body for updating account records. ```json { "firstName" : "Apex", "lastName": "Recipes", "phone" : "919-867-5309", "ExternalSalesforceId__c": " } ``` -------------------------------- ### StubExampleConsumer Constructor Source: https://github.com/trailheadapps/apex-recipes/blob/main/force-app/main/default/staticresources/documentation/StubExampleConsumer.md Initializes the class with a StubExample instance. ```apex public StubExampleConsumer(StubExample stub) ``` -------------------------------- ### Invoke findRelatedContacts from Apex Source: https://github.com/trailheadapps/apex-recipes/wiki/InvocableMethodRecipes Example of manually invoking the method by constructing the required request object and passing it as a list. ```apex Account account = new Account(name='awesome examples ltd.'); insert account; Contact contact = new Contact(accountId = account.id, firstName='Kevin', lastName='Awesome'); insert contact; InvocableMethodRecipes.ContactSearchRequest csr = new InvocableMethodRecipes.ContactSearchRequest(); csr.inputs = new List{account}; InvocableMethodRecipes.ContactSearchResult results = InvocableMethodRecipes.findRelatedContacts(csr); System.debug(results.output); ``` -------------------------------- ### Get Organization Record Source: https://github.com/trailheadapps/apex-recipes/wiki/OrgShape Fetches the read-only Organization record, suppressing CRUD warnings to allow universal access. ```apex private Organization getOrgRecord() ``` -------------------------------- ### Get Contact By Sender Method Signature Source: https://github.com/trailheadapps/apex-recipes/wiki/InboundEmailHandlerRecipes Method signature for retrieving or creating a contact based on the email sender. ```apex private Contact getContactBySender(Messaging.InboundEmail email) ``` -------------------------------- ### Initialize Method Constructor Source: https://github.com/trailheadapps/apex-recipes/wiki/TestDouble Constructor for creating a new Method instance with a name. ```apex public Method(String methodName) ``` -------------------------------- ### Enqueue QueueableChainingRecipes Source: https://github.com/trailheadapps/apex-recipes/wiki/QueueableChainingRecipes Use this command to initiate the execution of the QueueableChainingRecipes job. ```apex System.enqueueJob(new QueueableChainingRecipes()); ``` -------------------------------- ### Get Sum of Opportunity Records Signature Source: https://github.com/trailheadapps/apex-recipes/wiki/SOQLRecipes Defines the method signature for retrieving the sum of opportunity records for a specific account. ```apex public static Double getSumOfOpportunityRecords(Id accountId) ``` -------------------------------- ### Generate Apex Documentation Source: https://github.com/trailheadapps/apex-recipes/blob/main/README.md Command to generate Markdown documentation from Apex classes using the configured npm script. ```bash npm run apexdocs ``` -------------------------------- ### Build dynamic SOQL query with field list and where clause Source: https://github.com/trailheadapps/apex-recipes/wiki/DynamicSOQLRecipes Demonstrates building a query on the fly using a list of fields and a where clause. Requires careful sanitization of the where clause input. ```apex List fields = new List{ 'Name', 'NumberOfEmployees', 'BillingAddress' }; String whereClause = 'id = \'' + String.escapeSingleQuotes(acctId) + '\''; List results = DynamicSOQLRecipes.simpleQueryBuilder( fields, whereClause ); System.debug(results); ``` -------------------------------- ### Get Organization Shape Source: https://github.com/trailheadapps/apex-recipes/wiki/OrgShape Retrieves the organization record with memoization, suppressing CRUD validation warnings as the object is always accessible. ```apex private Organization getOrgShape() ``` -------------------------------- ### Retrieve Recipe Code via Apex Source: https://github.com/trailheadapps/apex-recipes/wiki/FormattedRecipeDisplayController Demonstrates calling the getRecipeCode method to fetch class information. ```apex System.debug(FormattedRecipeDisplayController.getRecipeCode('FormattedRecipeDisplayController')); ``` -------------------------------- ### Execute GET callout to second org in Apex Source: https://github.com/trailheadapps/apex-recipes/wiki/CalloutRecipes Retrieves a list of Accounts from a target endpoint using the performRestCallout method. ```apex System.debug(CalloutRecipes.httpGetCalloutToSecondOrg()); ``` -------------------------------- ### Create a file from a blob attached to a record Source: https://github.com/trailheadapps/apex-recipes/wiki/FilesRecipes Creates a file from binary data and links it to a record. The file extension in the filename determines the file type. ```apex Blob fileContents = Blob.valueOf('Hello World 2'); Account acct = [SELECT Id FROM Account LIMIT 1]; FilesRecipes.createFileAttachedToRecord( fileContents, firstLocation, 'AwesomeFile1' ); System.debug('Look for files assoicated with account: ' + acct.id); ``` -------------------------------- ### Get Unknown Object Type Signature Source: https://github.com/trailheadapps/apex-recipes/wiki/TestHelper Defines the method signature for retrieving the string representation of an object's class type. ```apex public static String getUnknownObjectType(Object obj) ``` -------------------------------- ### Invoke GET Request for Custom REST Endpoint Source: https://github.com/trailheadapps/apex-recipes/wiki/CustomRestEndpointRecipes Use this cURL command to retrieve data from a Salesforce custom REST endpoint. ```sh curl -H "Authorization: Bearer " "https:///services/apexrest/integration-service" ``` -------------------------------- ### Generate Sample Junction Object Data Source: https://github.com/trailheadapps/apex-recipes/blob/main/README.md Execute this command in the Developer Console to populate the org with sample data required for junction objects. ```apex DataFactoryForPackageInstalls.generateData(); ``` -------------------------------- ### Get Org Cache Partition Source: https://github.com/trailheadapps/apex-recipes/wiki/OrgShape Discovers a usable cache partition, memoizing the result to ensure the SOQL query runs only once per transaction. ```apex private Cache.OrgPartition getAvailableOrgCachePartition() ``` -------------------------------- ### Get current Quiddity value in Apex Source: https://github.com/trailheadapps/apex-recipes/wiki/QuiddityRecipes Retrieves the current request's Quiddity value. Use this to determine the execution context of the current Apex transaction. ```apex public static Quiddity demonstrateGetQuiddity() ``` -------------------------------- ### Publish a Platform Event with Callbacks Source: https://github.com/trailheadapps/apex-recipes/wiki/PlatformEventRecipes Publishes an Event_Recipes_Demo__e platform event using the publishEventWithCallbacks method, requiring the event to be created via sObjectType.newSObject to obtain an EventUuid. ```apex Account acct = new Account(Name = 'Awesome Events Ltd.'); insert acct; // Creating the event via sObjectType.newSObject is required to obtain an EventUuid Event_Recipes_Demo__e event = (Event_Recipes_Demo__e) Event_Recipes_Demo__e.sObjectType.newSObject(null, true); event.AccountId__c = acct.Id; event.Title__c = 'Updated website'; event.Url__c = 'https://developer.salesforce.com'; PlatformEventRecipes.publishEventWithCallbacks(event); ``` -------------------------------- ### Batchable Interface Methods Source: https://github.com/trailheadapps/apex-recipes/wiki/BatchApexRecipes Required methods for implementing the Database.Batchable interface. ```apex public Database.QueryLocator start(Database.BatchableContext context) ``` ```apex public void execute(Database.BatchableContext context, List scope) ``` ```apex public void finish(Database.BatchableContext context) ``` -------------------------------- ### runScriptWithMultipleInputs(products, attributes, exchangeRates) Source: https://github.com/trailheadapps/apex-recipes/wiki/MultipleInputRecipes Converts shopping basket information into another currency by executing the /dw/multipleInputs.dwl DataWeave script with multiple JSON inputs. ```APIDOC ## runScriptWithMultipleInputs(products, attributes, exchangeRates) ### Description Converts the information of a shopping basket into another currency using a DataWeave script. ### Signature `public static String runScriptWithMultipleInputs(String products, String attributes, String exchangeRates)` ### Parameters - **products** (String) - Required - List of products in the form of a JSON string. - **attributes** (String) - Required - List of product attributes used as filters in the form of a JSON string. - **exchangeRates** (String) - Required - List of currency exchange rates in the form of a JSON string. ### Return Type - **String** - The script output as an XML string. ``` -------------------------------- ### EventInfo Constructor Source: https://github.com/trailheadapps/apex-recipes/wiki/PlatformEventPublishCallback Initializes the EventInfo data object with a UUID and account ID. ```apex public EventInfo(String eventUuid, Id accountId) ``` -------------------------------- ### Initialize ApiServiceRecipes Source: https://github.com/trailheadapps/apex-recipes/blob/main/force-app/main/default/staticresources/documentation/ApiServiceRecipes.md Default constructor that binds the service to the configured Named Credential. ```apex public ApiServiceRecipes() ``` -------------------------------- ### Publish a Platform Event Source: https://github.com/trailheadapps/apex-recipes/wiki/PlatformEventRecipes Publishes an Event_Recipes_Demo__e platform event using the publishEvent method. ```apex Account acct = new Account(Name = 'Awesome Events Ltd.'); insert acct; Event_Recipes_Demo__e evt = new Event_Recipes_Demo__e(AccountId__c = acct.id, Title__c='Updated website', Url__c = 'https://developer.salesforce.com'); Database.saveResults result = PlatformEventsRecipes.publishEvent(evt); System.debug(result); ``` -------------------------------- ### Create Files By Email Attachments Method Signature Source: https://github.com/trailheadapps/apex-recipes/wiki/InboundEmailHandlerRecipes Helper method signature for bulk saving email attachments. ```apex private void createFilesByEmailAttachments(List inboundAttachments, Id contactId) ``` -------------------------------- ### PlatformEventPublishCallback Constructor Source: https://github.com/trailheadapps/apex-recipes/wiki/PlatformEventPublishCallback Initializes the callback handler with a list of event information objects. ```apex public PlatformEventPublishCallback(List eventInfos) ``` -------------------------------- ### Safely Fluent Configuration Methods Source: https://github.com/trailheadapps/apex-recipes/wiki/Safely Methods to configure the Safely instance before executing DML operations. ```apex public Safely allOrNothing() ``` ```apex public Safely throwIfRemovedFields() ``` -------------------------------- ### Convenience makeApiCall methods Source: https://github.com/trailheadapps/apex-recipes/wiki/IterableApiClient Overloaded convenience methods for making HTTP callouts with varying levels of parameter abstraction. ```apex protected HttpResponse makeApiCall(HttpVerb method, String path, String query, String body) ``` ```apex protected HttpResponse makeApiCall(HttpVerb method, String path, String query) ``` ```apex protected HttpResponse makeApiCall(HttpVerb method, String path) ``` -------------------------------- ### Initialize RestClient with Named Credential Source: https://github.com/trailheadapps/apex-recipes/wiki/RestClient Constructor used to initialize the client with a specific Named Credential. ```apex public RestClient(String namedCredential) ``` -------------------------------- ### Define exampleObject field Source: https://github.com/trailheadapps/apex-recipes/wiki/ApiServiceRecipesDataModel Represents a nested object property for JSON serialization. ```apex public exampleObject ``` -------------------------------- ### Define exampleColor field Source: https://github.com/trailheadapps/apex-recipes/wiki/ApiServiceRecipesDataModel Represents a string property for JSON serialization. ```apex public exampleColor ``` -------------------------------- ### Define ExampleObject field a Source: https://github.com/trailheadapps/apex-recipes/wiki/ApiServiceRecipesDataModel Represents a string field within the nested ExampleObject class. ```apex public a ``` -------------------------------- ### Initialize LDVRecipes with offsetId Source: https://github.com/trailheadapps/apex-recipes/wiki/LDVRecipes Constructor for continuing the queueable chain using an offset ID. ```apex public LDVRecipes(Id offsetId) ``` -------------------------------- ### Query Accounts with WHERE Clause Source: https://github.com/trailheadapps/apex-recipes/wiki/SOQLRecipes Demonstrates filtering records using a basic WHERE clause. ```apex System.debug(SOQLRecipes.getRecordsByFieldValue()); ``` -------------------------------- ### Configure Method Behavior Source: https://github.com/trailheadapps/apex-recipes/wiki/TestDouble Methods for configuring parameters, return values, and exceptions for a stubbed method. ```apex public Method withParamTypes(List paramTypes) ``` ```apex public Method withParamNames(List paramNames) ``` ```apex public Method withArgs(List args) ``` ```apex public Method returning(Object returnValue) ``` ```apex public Method throwing(String exceptionMessage) ``` -------------------------------- ### Query Accounts with LIMIT Clause Source: https://github.com/trailheadapps/apex-recipes/wiki/SOQLRecipes Demonstrates restricting the number of returned records using the LIMIT clause. ```apex System.debug(SOQLRecipes.getSpecificNumberOfRecords()); ``` -------------------------------- ### IterableApiClient constructor Source: https://github.com/trailheadapps/apex-recipes/wiki/IterableApiClient Initializes the client with a specific Named Credential. ```apex public IterableApiClient(String namedCredential) ``` -------------------------------- ### Execute simple dynamic SOQL query Source: https://github.com/trailheadapps/apex-recipes/wiki/DynamicSOQLRecipes Demonstrates a basic dynamic SOQL query defined in Apex without input parameters. ```apex System.debug(DynamicSOQLRecipes.simpleDynamicSOQLQuery()); ``` -------------------------------- ### run() Source: https://github.com/trailheadapps/apex-recipes/wiki/LogTriggerHandler The main brokering method called by the trigger to determine the execution context and invoke the appropriate handler method. ```APIDOC ## run() ### Description This is the main brokering method that is called by the trigger. It is responsible for determining the proper context and calling the correct method. ### Signature `public virtual void run()` ### Example ```apex AccountTriggerHandler.run(); ``` ``` -------------------------------- ### Define FileAndLinkObject fileName property Source: https://github.com/trailheadapps/apex-recipes/blob/main/force-app/main/default/staticresources/documentation/FilesRecipes.md Represents the name of the file as a String. ```apex public fileName ``` -------------------------------- ### Query Accounts with OFFSET Source: https://github.com/trailheadapps/apex-recipes/wiki/SOQLRecipes Demonstrates retrieving a specific subset of records using the OFFSET clause. ```apex System.debug(SOQLRecipes.getSecond10AccountRecords()); ``` -------------------------------- ### Insert Account via Keyword in System Mode Source: https://github.com/trailheadapps/apex-recipes/wiki/DMLRecipes Persists a new account record using the insert keyword in system mode. ```apex DMLRecipes.insertAccountViaInsertKeywordInSystemMode('Hello'); ``` -------------------------------- ### Assign Permission Set Source: https://github.com/trailheadapps/apex-recipes/blob/main/README.md Grant the necessary permissions to the default user to access the Apex Recipes app. ```bash sf org assign permset -n Apex_Recipes ``` -------------------------------- ### Loop Over SOQL Query Results Source: https://github.com/trailheadapps/apex-recipes/wiki/SOQLRecipes Demonstrates iterating over a SOQL query result set. ```apex System.debug(SOQLRecipes.getLargeNumberOfRecords()); ``` -------------------------------- ### Search Picklist Buckets with Values Source: https://github.com/trailheadapps/apex-recipes/wiki/CustomMetadataUtilties Returns a list of bucket names matching a search term based on the provided bucketed picklist metadata. ```apex public List getPicklistBucketWithValues(List bPL, String search) ``` -------------------------------- ### Authorize Hub Org Source: https://github.com/trailheadapps/apex-recipes/blob/main/README.md Authenticates the Salesforce CLI with your Dev Hub org. ```bash sf org login web -d -a myhuborg ``` -------------------------------- ### Constructor Signature Source: https://github.com/trailheadapps/apex-recipes/wiki/AccountTriggerHandler Constructor for initializing class variables based on trigger context. ```apex public AccountTriggerHandler() ``` -------------------------------- ### POST Request Methods Source: https://github.com/trailheadapps/apex-recipes/wiki/ApiServiceRecipes Convenience methods for performing POST requests with optional query parameters. ```apex protected HttpResponse post(String path, String body) ``` ```apex protected HttpResponse post(String path, String query, String body) ``` -------------------------------- ### Execute dynamic SOQL with field binding Source: https://github.com/trailheadapps/apex-recipes/wiki/DynamicSOQLRecipes Demonstrates using a field from a passed parameter in a bound dynamic SOQL query. ```apex Account acct = [SELECT Name FROM Account WHERE Name = 'hello' LIMIT 1]; Account[] results = DynamicSOQLRecipes.dynamicFieldsBindingSOQLQuery(acct); System.debug(results); ``` -------------------------------- ### Initialize LoopCount Source: https://github.com/trailheadapps/apex-recipes/wiki/TriggerHandler Constructors for setting the maximum loop threshold. ```apex public LoopCount() ``` ```apex public LoopCount(Integer max) ``` -------------------------------- ### getGreeting() Source: https://github.com/trailheadapps/apex-recipes/wiki/StubExampleConsumer Retrieves the greeting string from the stub. ```APIDOC ### Method `public String getGreeting()` #### Returns - **String** - The greeting string. ``` -------------------------------- ### MetadataTriggerService Constructor Source: https://github.com/trailheadapps/apex-recipes/wiki/MetadataTriggerService Initializes the service with the specified object type name. ```apex public MetadataTriggerService(String objectTypeName) ``` -------------------------------- ### Define exampleArray field Source: https://github.com/trailheadapps/apex-recipes/wiki/ApiServiceRecipesDataModel Represents a list of integers for JSON serialization. ```apex public exampleArray ``` -------------------------------- ### Execute Batch Apex Source: https://github.com/trailheadapps/apex-recipes/wiki/BatchApexRecipes Use this command to trigger the execution of the BatchApexRecipes batch job. ```apex Database.executeBatch(new BatchApexRecipes()); ``` -------------------------------- ### Log Class Constructor Signature Source: https://github.com/trailheadapps/apex-recipes/wiki/Log Private constructor to enforce the singleton pattern. ```apex private Log() ``` -------------------------------- ### Assign Permission Sets Source: https://github.com/trailheadapps/apex-recipes/blob/main/README.md Grants necessary permissions to the default user for the application. ```bash sf org assign permset -n Apex_Recipes sf org assign permset -n Walkthroughs ``` -------------------------------- ### Set greeting methods Source: https://github.com/trailheadapps/apex-recipes/wiki/StubExample Overloaded methods to set the greeting field using either a String or an Integer. ```apex public void setGreeting(String greeting) ``` ```apex public void setGreeting(Integer greeting) ``` -------------------------------- ### Initialize LogTriggerHandler Source: https://github.com/trailheadapps/apex-recipes/wiki/LogTriggerHandler Constructor used to instantiate the handler for processing log records. ```apex public LogTriggerHandler() ``` -------------------------------- ### Define exampleNumber field Source: https://github.com/trailheadapps/apex-recipes/wiki/ApiServiceRecipesDataModel Represents an integer property for JSON serialization. ```apex public exampleNumber ``` -------------------------------- ### Make API Call with Default Headers Source: https://github.com/trailheadapps/apex-recipes/wiki/ApiServiceRecipes Static wrapper for executing HTTP requests that assumes default headers. ```apex public static HttpResponse makeApiCall(String namedCredential, HttpVerb method, String path, String query) ``` ```apex System.Debug(RestClient.makeApiCall('GoogleBooksAPI', RestClient.HttpVerb.GET, 'volumes', 'q=salesforce')); ``` -------------------------------- ### createFilesAttachedToRecords(List toCreate) Source: https://github.com/trailheadapps/apex-recipes/wiki/FilesRecipes Bulk method for inserting multiple files and linking them to records. ```APIDOC ## public static List createFilesAttachedToRecords(List toCreate) ### Description Bulk method for inserting multiple files and link them to records. ### Parameters - **toCreate** (List) - Required ### Return Type List ``` -------------------------------- ### Define FileAndLinkObject fileContents property Source: https://github.com/trailheadapps/apex-recipes/blob/main/force-app/main/default/staticresources/documentation/FilesRecipes.md Represents the content of the file as a Blob. ```apex public fileContents ``` -------------------------------- ### Define exampleCouldBeNull field Source: https://github.com/trailheadapps/apex-recipes/wiki/ApiServiceRecipesDataModel Represents a nullable string property for JSON serialization. ```apex public exampleCouldBeNull ``` -------------------------------- ### PlatformEventPublishCallback(eventInfos) Source: https://github.com/trailheadapps/apex-recipes/blob/main/force-app/main/default/staticresources/documentation/PlatformEventPublishCallback.md Constructor for the PlatformEventPublishCallback class. ```APIDOC ## Constructor: PlatformEventPublishCallback(eventInfos) ### Description Initializes a new instance of the PlatformEventPublishCallback class with a list of event information objects. ### Signature `public PlatformEventPublishCallback(List eventInfos)` ### Parameters - **eventInfos** (List) - Required - A list of EventInfo objects containing event details. ``` -------------------------------- ### MetadataTriggerService(String objectTypeName) Source: https://github.com/trailheadapps/apex-recipes/wiki/MetadataTriggerService Constructor to initialize the service for a specific sObject type. ```APIDOC ## Constructor: MetadataTriggerService(String objectTypeName) ### Description Initializes a new instance of the MetadataTriggerService for the specified sObject type. ### Parameters - **objectTypeName** (String) - The API name of the sObject to manage triggers for. ``` -------------------------------- ### Convenience REST API Callout Methods Source: https://github.com/trailheadapps/apex-recipes/wiki/CalloutRecipes Simplified versions of the makeApiCall method that assume default headers or omit optional parameters. ```apex protected HttpResponse makeApiCall(HttpVerb method, String path, String query, String body) ``` ```apex protected HttpResponse makeApiCall(HttpVerb method, String path, String query) ``` -------------------------------- ### atFutureMethodWithCalloutPrivileges(url) Source: https://github.com/trailheadapps/apex-recipes/wiki/AtFutureRecipes Demonstrates the @future annotation for asynchronous execution with HTTP callout privileges. ```APIDOC ## public static void atFutureMethodWithCalloutPrivileges(String url) ### Description Method demonstrates how an @future annotated method can make an HTTP Callout. This method also demonstrates the necessary steps to make an HTTP callout without the RestClient abstraction layer. ### Parameters - **url** (String) - Required - The URL to make a callout to. ### Return Type void ### Example AtFutureRecipes.atFutureMethodWithCalloutPrivileges('google.com'); ``` -------------------------------- ### Log.get() Source: https://github.com/trailheadapps/apex-recipes/wiki/Log Retrieves the singleton instance of the Log class. ```APIDOC ## public static Log get() ### Description Singleton pattern method to retrieve the Log instance. ### Return Type Log ``` -------------------------------- ### handleMethodCall(...) Source: https://github.com/trailheadapps/apex-recipes/wiki/TestDouble Required method for the StubProvider interface used to delegate responses to the appropriate Method object. ```APIDOC ## handleMethodCall(Object stubbedObject, String stubbedMethodName, Type returnType, List listOfParamTypes, List listOfParamNames, List listOfArgs) ### Description Required method for the StubProvider interface. This method is used to delegate response to the appropriate Method object, matched by name and parameters. ### Signature `public Object handleMethodCall(Object stubbedObject, String stubbedMethodName, Type returnType, List listOfParamTypes, List listOfParamNames, List listOfArgs)` ### Parameters - **stubbedObject** (Object) - Required - The object being stubbed - **stubbedMethodName** (String) - Required - The name of the Method being stubbed - **returnType** (Type) - Required - Return type - **listOfParamTypes** (List) - Required - List of parameter types - **listOfParamNames** (List) - Required - List of parameter names - **listOfArgs** (List) - Required - List of parameter values ### Return Type Object ``` -------------------------------- ### doLoad(String key) Source: https://github.com/trailheadapps/apex-recipes/blob/main/force-app/main/default/staticresources/documentation/PlatformCacheBuilderRecipes.md The doLoad method is required by the CacheBuilder interface. It returns an Object that is either calculated or retrieved from the cache based on the provided key. ```APIDOC ## doLoad(String key) ### Description The doLoad method is required by the CacheBuilder interface. It returns an Object that is either calculated or retrieved from the cache based on the provided key. ### Signature public Object doLoad(String key) ### Parameters - **key** (String) - Required - String used to help generate the Cache Key ### Return Type Object (The object should be casted at the call location) ### Example Account[] accounts = (Account[]) Cache.Session.get(PlatformCacheBuilderRecipes.class, 'myAccounts') ``` -------------------------------- ### Define Default Partition Constant Source: https://github.com/trailheadapps/apex-recipes/wiki/PlatformCacheRecipes Defines the default cache partition string constant used within the class. ```apex private static final DEFAULT_PARTITION ``` -------------------------------- ### Make API Call Source: https://github.com/trailheadapps/apex-recipes/wiki/CalloutRecipes Executes an HTTP request using a specified method and path without body or query parameters. ```apex protected HttpResponse makeApiCall(HttpVerb method, String path) ``` -------------------------------- ### doLoad(String key) Source: https://github.com/trailheadapps/apex-recipes/wiki/PlatformCacheBuilderRecipes The doLoad method is required by the Cache.CacheBuilder interface. It returns an Object that is either calculated or retrieved from the cache based on the provided key. ```APIDOC ## doLoad(String key) ### Description The doLoad method is required by the Cache.CacheBuilder interface. It is used to return a single Object that is either calculated by the method or retrieved from the cache using the provided key. ### Signature `public Object doLoad(String key)` ### Parameters - **key** (String) - The string used to help generate the Cache Key. ### Return Type **Object** - The object that should be casted at the call location. ### Example ```apex Account[] accounts = (Account[]) Cache.Session.get(PlatformCacheBuilderRecipes.class, 'myAccounts'); ``` ``` -------------------------------- ### Authorize Salesforce Org Source: https://github.com/trailheadapps/apex-recipes/blob/main/README.md Authenticate the Salesforce CLI with your target environment and set an alias. ```bash sf org login web -s -a mydevorg ``` -------------------------------- ### Execute Basic SOSL Search Source: https://github.com/trailheadapps/apex-recipes/wiki/SOSLRecipes Executes a basic SOSL search and outputs the results to the debug log. ```apex System.debug(SOSLRecipes.basicSOSLSearch()); ``` -------------------------------- ### stripInaccessibleFromQuery() Source: https://github.com/trailheadapps/apex-recipes/wiki/StripInaccessibleRecipes Demonstrates how to use stripInaccessible to remove fields and objects from query results. ```APIDOC ## public static List stripInaccessibleFromQuery() ### Description Demonstrates how to use stripInaccessible to remove fields and objects from a queries results. ### Return Type List ### Example System.debug(StripInaccessibleRecipes.stripInaccessibleFromQuery()); ``` -------------------------------- ### Log Class Method Signatures Source: https://github.com/trailheadapps/apex-recipes/wiki/Log Methods for managing the log buffer and publishing messages. ```apex public static Log get() ``` ```apex public void add(String messageToLog) ``` ```apex public void add(String messageToLog, LogSeverity severity) ``` ```apex public void add(Exception exceptionToLog) ``` ```apex public void add(Exception exceptionToLog, LogSeverity severity) ``` ```apex public void publish() ``` ```apex public void publish(Exception exceptionToLog) ``` ```apex public void publish(String messageToLog) ``` -------------------------------- ### Create Named Credential Method Source: https://github.com/trailheadapps/apex-recipes/wiki/NamedCredentialRecipes Creates a named credential using the provided wrapper and permission set. ```apex public static ConnectApi.NamedCredential createNamedCredential(ConnectApiWrapper connectApiWrapper, String permissionSetName) ``` ```apex System.debug(NamedCredentialRecipes.createNamedCredential(new ConnectApiWrapper(), 'Apex_Recipes')); HttpResponse response = RestClient.makeApiCall( NAMED_CREDENTIAL_DEVELOPER_NAME, RestClient.HttpVerb.GET, '/volumes?q=salesforce' ); System.debug(response.getBody()); ``` -------------------------------- ### Initialize LookupRelationshipDefinition Source: https://github.com/trailheadapps/apex-recipes/wiki/MetadataCatalogRecipes Creates a new instance of the LookupRelationshipDefinition class using a FieldDefinition object. ```apex FieldDefinition fd = [SELECT Id, DeveloperName, RelationshipNme, DataType FROM FieldDefinition LIMIT 1]; MetadataCatalogRecipes.LookupRelationshipDefinition lrd = new MetadataCatalogRecipes.LookupRelationshipDefinition(fd); System.debug(lrd); ``` -------------------------------- ### PATCH Request Convenience Method Source: https://github.com/trailheadapps/apex-recipes/wiki/CalloutRecipes Provides a simplified interface for executing PATCH HTTP requests. ```apex protected HttpResponse patch(String path, String query, String body) ``` -------------------------------- ### Execute queueable method Source: https://github.com/trailheadapps/apex-recipes/wiki/LDVRecipes The main execution method for processing chunks of records. ```apex public void execute(System.QueueableContext queueableContext) ``` -------------------------------- ### stripInaccessibleFromSubquery() Source: https://github.com/trailheadapps/apex-recipes/wiki/StripInaccessibleRecipes Demonstrates how to use stripInaccessible to remove fields and objects from primary and related child objects. ```APIDOC ## public static List stripInaccessibleFromSubquery() ### Description Demonstrates how to use stripInaccessible to remove fields and objects not only from the primary object but also from related child objects. ### Return Type List ### Example System.debug(StripInaccessibleRecipes.stripInaccessibleFromSubquery()); ``` -------------------------------- ### Initialize custom order comparator Source: https://github.com/trailheadapps/apex-recipes/wiki/AccountShippingCountryComparator Constructor that allows specifying the sort order as either ascending or descending. ```apex public AccountShippingCountryComparator(AccountShippingCountryComparator.SortOrder order) ``` -------------------------------- ### getDefaultPartition(type) Source: https://github.com/trailheadapps/apex-recipes/wiki/PlatformCacheRecipes Returns a partition for a given name and type. ```APIDOC ## public static Cache.Partition getDefaultPartition(PartitionType type) ### Description Returns a partition for a given name, and type. ### Parameters - **type** (PartitionType) - Required - the partition type ### Return Type Cache.Partition ``` -------------------------------- ### Execute dynamic SOQL with intelligent typecasting Source: https://github.com/trailheadapps/apex-recipes/wiki/DynamicSOQLRecipes Demonstrates using typecasting to ensure input is safe for dynamic queries, preventing injection by enforcing data types. ```apex System.debug(DynamicSOQLRecipes.typecastDataIntelligently(2).size()); ``` -------------------------------- ### CalloutRecipes(String namedCredential) Source: https://github.com/trailheadapps/apex-recipes/wiki/CalloutRecipes Constructor to initialize the CalloutRecipes instance with a specific Named Credential. ```APIDOC ## Constructor: CalloutRecipes(String namedCredential) ### Description Initializes the class with the name of the Named Credential to be used for subsequent callouts. ### Parameters - **namedCredential** (String) - Required - The name of the Named Credential to use. ``` -------------------------------- ### StubExampleConsumer Methods Source: https://github.com/trailheadapps/apex-recipes/blob/main/force-app/main/default/staticresources/documentation/StubExampleConsumer.md Methods for retrieving and setting values within the consumer class. ```apex public Boolean getIsTrue() ``` ```apex public String getGreeting() ``` ```apex public void setGreeting(String greeting) ``` ```apex public void setGreeting(Integer someInt) ``` ```apex public void setGreeting(Boolean someBoolean) ``` -------------------------------- ### Check create permissions with CanTheUser.create Source: https://github.com/trailheadapps/apex-recipes/wiki/CanTheUser Convenience methods to determine if the running user can create an object, accepting an SObject instance or an object name string. ```apex System.debug(CanTheUser.create(new Account())); ``` ```apex System.debug(CanTheUser.create('Account')); ``` -------------------------------- ### Execute POST callout to second org in Apex Source: https://github.com/trailheadapps/apex-recipes/wiki/CalloutRecipes Sends a serialized list of contact records to a second Salesforce org for insertion. ```apex List contacts = [SELECT id, firstName, lastName FROM Contact LIMIT 5]; System.debug(CalloutRecipes.httpPostCalloutToSecondOrg(contacts)); ``` -------------------------------- ### Undelete Account via Database Method Usage Source: https://github.com/trailheadapps/apex-recipes/wiki/DMLRecipes Demonstrates how to insert, delete, and then undelete an account using the DMLRecipes utility class. ```apex List accounts = new List{new Account(name = 'Hello World')}; insert accounts; delete accounts; List results = DMLRecipes.undeleteAccountViaDatabaseMethod(accounts, AccessLevel.USER_MODE); System.debug(results); ``` -------------------------------- ### Make API Call Methods Source: https://github.com/trailheadapps/apex-recipes/wiki/RestClient A collection of overloaded methods for executing HTTP requests with varying levels of detail. ```apex protected HttpResponse makeApiCall(HttpVerb method, String path, String query, String body, Map headers) ``` ```apex protected HttpResponse makeApiCall(HttpVerb method, String path, String query, String body) ``` ```apex protected HttpResponse makeApiCall(HttpVerb method, String path, String query) ``` ```apex protected HttpResponse makeApiCall(HttpVerb method, String path) ``` -------------------------------- ### Query Accounts with Bound Variable LIMIT Source: https://github.com/trailheadapps/apex-recipes/wiki/SOQLRecipes Demonstrates using a bound variable to dynamically define the LIMIT in a SOQL query. ```apex System.debug(SOQLRecipes.getFirstXRecords(5)); ``` -------------------------------- ### Invoke getSumOfOpportunityRecords Source: https://github.com/trailheadapps/apex-recipes/wiki/SOQLRecipes Demonstrates how to call the getSumOfOpportunityRecords method using an account ID. ```apex Id accountId = [SELECT Id FROM Account LIMIT 1].Id; System.debug(SOQLRecipes.getSumOfOpportunityRecords(accountId)); ``` -------------------------------- ### Log.publish() Source: https://github.com/trailheadapps/apex-recipes/wiki/Log Publishes the current buffer of log messages or adds a new message/exception and publishes immediately. ```APIDOC ## public void publish() ## public void publish(Exception exceptionToLog) ## public void publish(String messageToLog) ### Description Publishes messages currently in the buffer. Overloaded versions allow adding a single message or exception and publishing the entire buffer immediately. ### Parameters - **exceptionToLog** (Exception) - Exception to format and log. - **messageToLog** (String) - String to log. ``` -------------------------------- ### MetadataTriggerHandler Constructor Source: https://github.com/trailheadapps/apex-recipes/wiki/MetadataTriggerHandler Constructors for initializing the MetadataTriggerHandler, including a default constructor for live triggers and one accepting a service instance. ```apex public MetadataTriggerHandler() ``` ```apex public MetadataTriggerHandler(MetadataTriggerService mts) ``` -------------------------------- ### PUT Request Methods Source: https://github.com/trailheadapps/apex-recipes/wiki/ApiServiceRecipes Convenience methods for performing PUT requests with optional query parameters. ```apex protected HttpResponse put(String path, String body) ``` ```apex protected HttpResponse put(String path, String query, String body) ``` -------------------------------- ### Update Account via Keyword in System Mode Source: https://github.com/trailheadapps/apex-recipes/wiki/DMLRecipes Updates a list of accounts using the update DML keyword in system mode. ```apex Account acct = new Account(name='Hello World'); insert acct; DMLRecipes.updateAcccountViaKeywordInSystemMode(acct); ``` -------------------------------- ### Insert Account via Keyword in User Mode Source: https://github.com/trailheadapps/apex-recipes/wiki/DMLRecipes Persists a new account record using the insert keyword in user mode. ```apex DMLRecipes.insertAccountViaInsertKeywordInUserMode('Hello'); ``` -------------------------------- ### CanTheUser Methods Source: https://github.com/trailheadapps/apex-recipes/wiki/CanTheUser Methods for checking object-level and field-level security permissions. ```APIDOC ## CanTheUser.edit(List objs) / CanTheUser.edit(String objName) ### Description Determines if the running user can edit or update the specified object or list of objects. ### Signature `public static Boolean edit(List objs)` `public static Boolean edit(String objName)` ### Return Type Boolean --- ## CanTheUser.ups(SObject obj) / CanTheUser.ups(List objs) / CanTheUser.ups(String objName) ### Description Determines if the running user can upsert (insert and update) the specified object, list of objects, or object name. ### Signature `public static Boolean ups(SObject obj)` `public static Boolean ups(List objs)` `public static Boolean ups(String objName)` ### Return Type Boolean --- ## CanTheUser.destroy(SObject obj) / CanTheUser.destroy(List objs) / CanTheUser.destroy(String objName) ### Description Determines if the running user can delete or destroy the specified object, list of objects, or object name. ### Signature `public static Boolean destroy(SObject obj)` `public static Boolean destroy(List objs)` `public static Boolean destroy(String objName)` ### Return Type Boolean --- ## CanTheUser.flsAccessible(String obj, String field) ### Description Determines if a given field on a given object is accessible (readable) by the current user. ### Signature `public static Boolean flsAccessible(String obj, String field)` ### Return Type Boolean --- ## CanTheUser.bulkFLSAccessible(String obj, Set fields) ### Description Bulk version of flsAccessible to check multiple fields at once. ### Signature `public static Map bulkFLSAccessible(String obj, Set fields)` ### Return Type Map --- ## CanTheUser.flsUpdatable(String obj, String field) ### Description Determines if a given field on a given object is updatable by the current user. ### Signature `public static Boolean flsUpdatable(String obj, String field)` ### Return Type Boolean ``` -------------------------------- ### iterateOnAccountList(accounts) Source: https://github.com/trailheadapps/apex-recipes/wiki/IterationRecipes Demonstrates how to iterate on a list of SObjects using the Iterable and Iterator interfaces to calculate the sum of the 'number of employees' field. ```APIDOC ## iterateOnAccountList(accounts) ### Description Demonstrates how to iterate on a list of SObjects using the Iterable and Iterator interfaces. This example iterates on Accounts to sum the 'number of employees' field values. ### Signature `public static Integer iterateOnAccountList(List accounts)` ### Parameters - **accounts** (List) - Required - A list of accounts that will be iterated on. ### Return Type **Integer** - Total number of employees for the accounts. ``` -------------------------------- ### Compare method signature for Account sorting Source: https://github.com/trailheadapps/apex-recipes/wiki/AccountNumberOfEmployeesComparator Defines the signature for the compare method used to sort Account objects by employee count. ```apex public Integer compare(Account a1, Account a2) ``` -------------------------------- ### getPicklistBucketWithValues(List bPL, String search) Source: https://github.com/trailheadapps/apex-recipes/wiki/CustomMetadataUtilties Returns a list of bucket names that match the given search term and associated fields. ```APIDOC ## getPicklistBucketWithValues(List bPL, String search) ### Description Returns a list of bucket names that match the given search term, and a list of possible fields. ### Parameters - **bPL** (List) - Required - Bucketed Picklist list. - **search** (String) - Required - Search String for Bucketed_Picklist_Value__mdt.label. ### Return Type List ``` -------------------------------- ### Create External Credential Method Source: https://github.com/trailheadapps/apex-recipes/wiki/NamedCredentialRecipes Creates an external credential for authentication and authorization purposes. ```apex private static ConnectApi.ExternalCredential createExternalCredential(ConnectApiWrapper connectApiWrapper, String permissionSetName) ``` ```apex System.debug(NamedCredentialRecipes.createExternalCredential(new ConnectApiWrapper(), 'Apex_Recipes')); ``` -------------------------------- ### Retrieve Bucketed Picklists for a List of Object IDs Source: https://github.com/trailheadapps/apex-recipes/wiki/CustomMetadataUtilties Convenience method that accepts a list of IDs and processes the first entry. ```apex public List getBucketedPicklistsForObject(List objIds) ```