salesforce-learning-note

  • 1. Task 1. Learn Apex, Trigger, and the simple use of object fields
    • 1.1. File upload
    • 1.2. Permission control
    • 1.3. SOQL
    • 1.4. Trigger
    • 1.5. Learning Apex
      • 1.5.1. List
  • 2. Task 2. Learn the development of Visualforce pages and be able to make Visualforce pages that interact with the background
    • 2.1. Visualforce generates PDF
      • 2.1.1. Pitfall records
    • 2.2. apex:pageBlockButtons style adjustment, before modification:
    • 2.3. After modification
      • 2.3.1. Code
    • 2.4. Official website explanation:
  • 3. Task 3. Learn some configuration functions within Salesforce, such as Flow, verification rules, repeat & match rules, approval flow configuration, etc.
    • 3.1. Trampling on pitfalls
    • 3.2. Three general types of flows (Flow)
    • 3.3. Three types of triggers (Trigger)
    • 3.4. Validation Rules
    • 3.5. Duplicate & Matching Rules
    • 3.6. Approval Processes
    • 3.7. official reference:
  • 4. Task 4. Learn the main asynchronous operations in Apex 1. Scheduled Job, 2. Batch, 3. Asynchronous method (Future), etc.
    • 4.1. 1.ScheduledApex
    • 4.2. 2. The steps to implement batch processing are clear, and you only need to perform the following steps:
    • 4.3. 3. The Future method is used for asynchronous processing and is often used in Web service callout operations.
      • 4.3.1. QA
        • 4.3.1.1. What is Batch? What problems can Batch be used to solve?
        • 4.3.1.2. Why do we need to use Batch to process large batches of data?
        • 4.3.1.3. How to enable Batch? How to set up batches?
        • 4.3.1.4. What modules is Batch divided into? What functions are implemented respectively?
        • 4.3.1.5. Database.query() can only query up to 50,000 pieces of data. What if the data I want to process exceeds 50,000 pieces?
  • 5. Task 5. Learn to print logs and troubleshoot problems based on logs
    • 5.1. reference
    • 5.2. Display debug only in vscode
    • 5.3. Anonymous class execution in vscode
    • 5.4. Logs
      • 5.4.1. Print log
      • 5.4.2. View logs:
    • 5.5. Testing
      • 5.5.1. Verification results
      • 5.5.2. Distinguishing test boundaries
      • 5.5.3. Testing Visualforce Controllers
      • 5.5.4. Testing Private variables and methods
        • 5.5.4.1. reference here
  • 6. vscode configuration
    • 6.1. prettier – code formatting tool,
  • 7. Playground login myths

1. Task 1. Learn Apex, Trigger, and the simple use of object fields

1.1. File upload

When passing, pay attention to the Blob object. If the Blob object is bound to the inputFile in the front end, be careful to use the transient statement or set the value to empty after insert.

  • https://www.cnblogs.com/zero-zyq/p/5752978.html

1.2. Permission control

Profile

PermissionSet

Role-hierarchical control
The superior role can see the data of the subordinate role. A is the superior of role B.

sharing rule and custom sharing

code sharing

1.3. SOQL

  • Use SOQL for loop to process query results that return multiple records to avoid heap size limitations. The disadvantage is that it takes a long time (including higher CPU time). If you encounter bottlenecks, consider using asynchronous loading.
  • Querying first and then processing uses space for time, which is highly efficient but also takes up a lot of memory.

1.4. Trigger

Custom actions can be performed on records in Salesforce (such as insert, update, or delete) before or after an event occurs. Just like database systems support triggers, Apex also provides trigger support to manage records.

1.before is used to update or validate record values, before saving them to the database

2.after is used to access field values set by the system and affect changes in other records. The record that fires the after trigger is read-only

1.5. Learning Apex

1.5.1. List

In Salesforce Apex, a List is a dynamically sized collection used to store various types of data. Although a List has no fixed length limit, it is subject to Salesforce platform limitations and resource constraints.

In Apex, the size of the List is affected by the heap memory limit. The heap memory limit depends on whether your Apex code executes in a synchronous environment (such as triggers, Visualforce controllers, etc.) or an asynchronous environment (such as batch classes, scheduled classes, etc.).

Here are some examples of Salesforce Apex heap memory limits:

  • Synchronous transactions: 6 MB
  • Asynchronous transactions: 12 MB

For example, if you use List in an Apex trigger, the heap memory limit is 6 MB when initializing and manipulating the list. Note that this restriction applies not just to Lists, but to all variables and data structures in the entire transaction.

To avoid encountering memory limits at runtime, the following best practices are recommended:

  • Only initialize and use the List when needed to avoid unnecessary memory usage throughout the transaction.
  • live.
  • When possible, use batch Apex and other asynchronous operations to process large amounts of data to alleviate memory constraints.
  • Limit operations on large Lists to avoid performing memory-intensive operations in loops.

2. Task 2. Learn the development of Visualforce pages and be able to make Visualforce pages that interact with the background

2.1. Visualforce generates PDF

  • reference: https://www.cnblogs.com/luqinghua/p/9326665.html

2.1.1. Pitfall records

Q:Attempt to de-reference a null object

A: Obtain the operation of the Description field from the Opportunity object. This error will occur when trying to operate on the Description field if your query does not find any Opportunity objects, or if the Opportunity objects found have a null Description field.

This problem can be solved by checking whether the Description field is null before using it. If it is null, you can choose to skip operating on it, or assign it a default value

public void spliteString(String s){<!-- -->
    if (s != null) {<!-- -->
        Index + + ;
        IndexList.add(String.valueOf(Index));
        List<String> str = s.split('\\
');
        List<String> str_temp;
        List<List<String>> sTable = new List<List<String>>();
        for(String tr:str){<!-- -->
            str_temp = new List<String>();
            for(Integer i=0;i<tr.length();i + + ){<!-- -->
                str_temp.add(tr.subString(i,i + 1));
            }
            sTable.add(str_temp);
        }
        ContentList.add(sTable);
        ContentMap.put(String.valueOf(Index),sTable);
    }
}

2.2. apex:pageBlockButtons style adjustment, before modification:

image

2.3. After modification

image

2.3.1. Code

<apex:pageBlockButtons location="bottom">

2.4. Official website explanation:

location String The area of the page block where the buttons should be rendered. Possible values include “top”, “bottom”, or “both”. If not specified, this value defaults to “both”.
The page block area where the button should be rendered. Possible values include “top”, “bottom”, or “both”. If not specified, this value defaults to “both”.
Note: If a pageBlock header facet is defined, the facet overrides the buttons that would normally appear at the top of the page block. Likewise, if a pageBlock footer facet is defined, the facet overrides the buttons that would normally appear at the bottom of the page block.
Note: If a page block title facet is defined, that facet will override the button that normally appears at the top of the page block. Likewise, if a pageBlock footer facet is defined, that facet will override the buttons that normally appear at the bottom of the page block.

3. Task 3. Learn some configuration functions within Salesforce, such as Flow, verification rules, repeat & match rules, approval flow configuration, etc.

  • Validation rules: https://trailhead.salesforce.com/zh-CN/content/learn/modules/point_click_business_logic/validation_rules

  • Duplicate & Match Rules: https://trailhead.salesforce.com/content/learn/modules/sales_admin_duplicate_management

  • Approval flow: https://trailhead.salesforce.com/content/learn/modules/business_process_automation

3.1. Trampling on pitfalls

  • The Username of Owner:User.Username is a name similar to the mailbox format instead of the full name.

3.2. Three general types of flows (Flow)

Flow Type Launched By Description
Screen Flow Quick action Screen Flows provide a UI that guides users through a business process.
Lightning page Screen flow provides a UI that guides users through business processes.
Experience Cloud site, and more
Autolaunched Flow Another flow Autolaunched Flows automate business processes that have no UI. They have no trigger and they run in the background.
Apex code Automatically started processes can Automate business processes without UI. They have no triggers and run in the background.
REST API
Triggered Flow Time Triggered Flows are autolaunched by a trigger you specify. They run in the background.
Data change The flow triggered is automatically started by the trigger you specify. They run in the background.
Platform event

3.3. Three types of triggers (Trigger)

Trigger Type When It Runs How To Use It
Schedule At A Time And Frequency You Specify Running Nightly Batch Jobs
Platform Event When A Particular Platform Event Message Is Received Subscribing To Events
Record When A Record Is Created , Updated, Or Deleted Updating Records And Sending Notifications

3.4. Validation Rules

Validation rules are a way to validate data when saving records. By creating validation rules, you can ensure that the data entered by users meets certain conditions when they save a record. Validation rules can be used to ensure that necessary fields are filled in, or that input data complies with business logic. When user-entered data does not comply with validation rules, the system displays an error message and prevents the record from being saved.

The steps to create a validation rule are as follows:

  • Log into Salesforce and go into settings.
  • In Settings, select “Object Management” and find the object for which you need to add validation rules.
  • Click Validation Rules and then click the New Validation Rule button.
  • On the Validation Rule Edit page, name the rule and enter the validation formula. The formula should return a boolean value (true or false). If the return value is true, the system displays an error message and prevents the record from being saved.
  • Enter the error condition formula, error message, and error location.
  • Save the rule.

3.5. Duplicate & Matching Rules

Duplicate and match rules are used to detect and prevent duplicate records. These rules identify potential duplicates by comparing new records to existing records. Matching rules define how two records are compared to determine whether they are similar. Duplicate rules define actions to be taken when duplicates are detected.

The steps to create duplicate and match rules are as follows:

  • Log into Salesforce and go into settings.
  • In Settings, select “Data Management” and find the “Duplicate and Matching Rules” option.
  • First, create a matching rule. Click the Matching Rules tab and then click the New Matching Rule button. Name the rule, select objects, and define matching conditions. Save the rule.
  • Next, create a repeating rule. Click the Repeating Rules tab and then click the New Repeating Rule button. Name the rule, select the object, and specify the matching rule to use. Define the action to be taken when a duplicate is detected, such as warning the user or preventing the record from being saved.
  • Save the rule.

3.6. Approval Processes

An approval process is an automated process that controls the approval of records. It ensures that records must meet specific conditions before they are approved by the relevant people. The approval process involves approvers, submitters, approval steps, approval actions and approval conditions.

The steps to create an approval process are as follows:

  • Log into Salesforce and go into settings. –
  • In Settings, select Process Automation and find the Approval Process option. –
  • Select the object for which you want to create an approval process and click the New Approval Process button. –
  • Name and provide a description for the approval process. Set entry conditions so that the approval process is only triggered when certain conditions are met. –
  • Define approval steps. Approval steps are stages of the approval process, each stage has one or more approvers. You can set approvers to specific users, roles, or sharing rules. At the same time, you can define the approval conditions for each approval step. –
  • Define approval actions. Approval actions can be triggered at various stages of the approval process, such as when a record is approved, rejected, or rolled back. Approval actions can include updating fields, sending email notifications, or triggering other automated processes. –
  • For each approval step, you can also set reminders and timeouts to ensure that approvers complete their approval within the specified time. –
  • Save approval processes and activate them when needed.

3.7. official reference:

https://trailhead.salesforce.com/en/content/learn/modules/record-triggered-flows/get-started-with-triggered-flows?trailmix_creator_id=strailhead & amp;trailmix_slug=wt23-automate-with- flow

4. Task 4. Learn the main asynchronous operations in Apex 1. Scheduled Job, 2. Batch, 3. Asynchronous method (Future), etc.

4.1. 1.ScheduledApex

This can be done by following these steps:

1. Implement the Scheduleable interface and override the execute method. The body of this method implements operations that need to be performed regularly;

2. Use the System.schedule() method to call scheduled tasks.

An example of the Schedulable interface code is as follows:

public class GoodsSchedule implements Schedulable {<!-- -->
    //Execute method contains scheduled tasks that need to be executed
    public void execute(SchedulableContext sc) {<!-- -->
        String queryString = 'select Id,GOODSNAME__c from GOODS__c';
        SimpleBatchUtil batchUtil = new SimpleBatchUtil(queryString);
        Database.executeBatch(batchUtil);
    }
}

4.2. 2. The steps to implement batch processing are clear, you only need to perform the following steps:

1. Implement the Database.Batchable interface;

2. Implement the start() method. In this method, query statements are usually written, and the data is passed to the execute() formal parameter through the Database.getQueryLocator(queryString) method. This method defines:

global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {<!-- -->};

3. Implement the execute() method, which performs DML operations on data. This method defines:

global void execute(Database.BatchableContext BC, list<p>){<!-- -->} ;

4. Implement the finish method (). This method performs post-processing. If there is no need for processing, it does not need to be processed.

4.3. 3. The Future method is used for asynchronous processing and is often used in Web service callout operations.

4.3.1. QA

4.3.1.1. What is Batch? What problems can Batch be used to solve?

Answer: Batch means batch processing, used to process large batches of data.

4.3.1.2. Why is it necessary to use Batch to process large batches of data?

answer:

  1. Because Salesforce has SQL DML limits, CPU Time Out, memory overrun and other limits for each transaction, directly processing large batches of data will lead to overruns.
  2. When Batch is processed in batches, each batch is a different transaction, and the number of DMLs is calculated separately, so overruns can be avoided to a large extent.
4.3.1.3. How to enable Batch? How to set up batches?
Database.executeBatch(new TestBatch());//When the batch quantity is not set, the default execution is 200 records per batch.
Database.executeBatch(new TestBatch(), 3000); // Set to execute 3000 records per batch, but in fact only 2000 records will be executed per batch, because the batch can only be set to 2000 at most, and if it exceeds 2000, it will be calculated as 2000
4.3.1.4. What are the modules of Batch? What functions are implemented respectively?
  1. start: used to query the total number of data to be processed (only executed once)
  2. execute: core method of batch processing, executes the main logic (executed multiple times)
  3. finish: A method executed after all batch processing is completed. It is generally used to send Batch error messages to designated users by email, such as sending error messages in Batch to the administrator, or sending Batch execution completion messages to the current user (only Executed once)
4.3.1.5. Database.query() can only query up to 50,000 pieces of data. What if the data I want to process exceeds 50,000 pieces?

You can use the Database.getQueryLocator() method to return up to 50 million records.

Future methods need to have several specifications:

1).The method must be static;

2). The @Future tag needs to be used above the method;

3).The method return type must be void type;

4). Method parameters must be private variables of the module and cannot be made public;

5). Method parameters are not allowed to use standard Object or sObject types, but basic types or collection types can be used;

6). A future method cannot call another future method, nor can it be called in a trigger when the future method is running;

7) The getContent() and getContentAsPDF() methods cannot be used in the future method.

The getContent() and getContentAsPDF() methods are synchronous calls in Salesforce Apex, which means that execution is paused during request processing until these methods complete their operation and return a result. This behavior can cause blocking and performance issues, especially when handling a large number of requests or operations that take a long time to complete.
The future method is designed to handle asynchronous operations, which allows operations to be queued for execution in the background, thus avoiding blocking or affecting other processes. Therefore, future methods do not support synchronous calls, such as getContent() and getContentAsPDF(), because these methods may cause blocking or delay, violating the asynchronous design principles of future methods.

The test future method is executed in the Test class. The difference from ordinary method testing is that the future method execution needs to be carried out in the Test.startTest() and Test.stopTest() methods. The following is the test code:
@isTest
private class Test_FutureSample {<!-- -->
    static testMethod void myUnitTest() {<!-- -->
        Test.startTest();
        List<ID> ids= new ID[]{<!-- -->'0012800000Hz6ozAAB','0012800000Hz6oxAAB'};
        FutureSample.futuremethod(ids);
        Test.stopTest();
    }
}

5. Task 5. Learn to print logs and troubleshoot problems based on logs

5.1. reference

  • https://trailhead.salesforce.com/content/learn/projects/find-and-fix-bugs-with-apex-replay-debugger/apex-replay-debugger-launch-playground
  • When the trace flag is enabled, Apex Code generates debug logs, which are records of all interactions within a transaction. The Apex Replay Debugger uses debug logs to simulate a live debugging session. It displays logged information, including variable values, call stacks, and breakpoints, similar to an interactive debugger

Apex Replay Debugger is a free tool that allows you to debug Apex code by inspecting debug logs using Visual Studio Code as a client. The Run Replay debugger provides the same functionality you expect from other debuggers. You can view variables, set breakpoints, and hover over variables to see their current values. You no longer need to manually parse thousands of log lines or fill System.debug code with statements to view variable values or trace code execution paths.

5.2. Display dubug only in vscode

https://thomas-prouvot.medium.com/salesforce-debug-with-vs-code-2604c8a71ce

5.3. Anonymous class execution in vscode

https://developer.salesforce.com/tools/vscode/en/apex/writing

That is, view the log in the console and convert it to vscode debugging.

5.4. Log

5.4.1. Print log

Using System.debug() in your code:

In Apex code, you can use the System.debug() method to output logs about variables, objects, exceptions, or other information at key points in your code.
You can also specify the log level, for example:

System.debug(LoggingLevel.ERROR, 'This is an error message');

5.4.2. View log:

In the Salesforce Developer Console, you can view the logs generated when Apex code is executed. You can also use setting the log level to filter the log information and only display the parts you care about.

To view the logs, open the Developer Console and execute your Apex code. Under the “Logs” tab you can find all generated logs.
Analyze the logs to troubleshoot the problem:

When viewing logs, you need to pay attention to the following points:

  • Look for information printed by System.debug() to learn about variable values, status, etc. during code execution.
  • Pay attention to the Exception or Error information in the log, which can help you locate the problem.
  • Observe the order in which the code is executed to make sure it executes in the expected order.
  • Pay attention to performance issues such as execution time, number of queries, etc.

5.5. Testing

5.5.1. Verification results

System.assert();
System.assertEquals();
System.assertNotEquals();

Use assert to ensure that the result output by the code is the value required by the business logic. In this way, after the code is deployed, if new code is added, the original test code can easily help check whether the new code destroys the old code, so there is no need to waste time testing the original logic again.

5.5.2. Differentiating test borders

Use Test.startTest() and Test.stopTest() to separate test data from the code to be tested. That is, create test data before startTest(), call the code to be tested in startTest() and stopTest(), and use assert to verify the test results after stopTest().

5.5.3. Testing Visualforce Controllers

  • Use Test.setCurrentPage() to allocate a simulated VF page to test the controller – ApexPages.CurrentPage().
  • Set HTTP parameters so that the controller can obtain the parameters in the URL.
  • Verify the jump result of the page
PageReference myPage = Page.MyPage;
myPage.getParameters().put('id', acc.Id);
Test.setCurrentPage(myPage);

MyPageController controller = new MyPageController();

5.5.4. Testing Private variables and methods

@TestVisible can make private variables and methods in the class accessible in the test class.

5.5.4.1. reference here
  • http://blog.meginfo.com.cn/how-to-write-good-apex-test-methods/
  • https://www.cnblogs.com/zero-zyq/p/5474874.html

6. vscode configuration

  • Salesforce Core Configuration setting Detect Conflicts At Sync: on, you can detect conflicts before uploading. You need to use comment instead of right mouse button to upload (may not work)
  • Domestic reference: https://juejin.cn/post/7094879891325190180

6.1. prettier – code formatting tool,

  • Related configuration reference: https://salesforce.stackexchange.com/questions/320884/use-prettier-in-vs-code-to-format-visualforce
  • VF configuration: https://github.com/forcedotcom/salesforcedx-vscode/issues/3383

7. Playground login myths

How to find the username during vscode authentication: https://trailhead.salesforce.com/help?article=Find-the-username-and-password-for-your-Trailhead-Playground

It seems that every pg needs to reset pd, which is very troublesome.
外The link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly
外The link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly
ions/320884/use-prettier-in-vs-code-to-format-visualforce

  • VF configuration: https://github.com/forcedotcom/salesforcedx-vscode/issues/3383

7. Playground login myths

How to find the username during vscode authentication: https://trailhead.salesforce.com/help?article=Find-the-username-and-password-for-your-Trailhead-Playground

It seems that every pg needs to reset pd, which is very troublesome.
[External link pictures are being transferred…(img-HqMDuKE3-1697504820060)]
[External link pictures are being transferred…(img-SVM6KD7r-1697504820061)]