Should you Upgrade Components API Version

In every new release Salesforce increase the API version by one. The version is relevant for classes/trigger/pages/components and determine which features are available.


For example, if Salesforce added a new field on the Account object in v55 and you need to use this feature, then your code must use v55 or later.


The following code won't compile if trying to save with version lower than 53, as the field Tier was introduce only at v53



public with sharing class AccountService{
	public static List<Account> getAllAccount(){
		return [SELECT Id,Tier FROM Account LIMIT 10];    
	}
}

*Just to clarify, you cannot rely on the compiler, as apex can access fields dynamically!


  • Flow also has an API version, but it should be noted that the features for API versions for Flow are not necessarily synchronized with those for the Apex code. For that reason I left the Flow outside the scope of this article.

Should we always use the latest version? 

When we create a new component it will usually be created with the highest available API version (if it is done using external tool, like vscode, then it might depend on the tool configuration), but is it the right choice?

It is highly recommended that all the code components will use the same API version. Otherwise you might get weird errors in some cases, as one component can access a set of features that are not accessible by other component.

As an example, consider service class that retrieve all the account fields dynamically with v52


public with sharing class AccountService{
    public static List<Account> getAllAccount(){
        String allFields = '';
        
        for(String field : Account.getSobjectType().getDescribe().fields.getMap().keyset()){
            allFields += field + ',';
        }
    
        return Database.query('SELECT ' + allFields.removeEnd(',') + ' FROM Account Limit 10');
    }
}

Other class with API v53 uses this service and try to access the field Tier:


public with sharing class ContactService{

    public static void manageContact(){
        List<Account> accountList = AccountService.getAllAccount();
        for(Account acc : accountList){
            System.debug('Tier:: ' + acc.Tier);
        }
    }
}

Running the method manageContact will result in run time error:

    System.SObjectException: SObject row was retrieved via SOQL

without querying the requested field: Account.Tier


Using the same API across all items will determine if the field Tier is accessible or not.

Of course, if all our code use v52 and per requirement we need to use the Tier field, then we need to upgrade our API version.


Should we upgrade all our previous code when new API version is introduce? 

Most likely it won't be a good idea. Any new API version might contains lots of other changes (included deprecated features), and therefore we must make sure that all our pervious implementation is still working with the new API (full regression!)


  • Be careful during a time when a new Salesforce release is available only in a sandbox. During this period, components can use the new API version, but it will not be possible to deploy them to the production environment, where the new API is not yet available.


You can construct an upgrade plan in your company. For example, upgrade all the components API once in a year or any period that match the company needs and resources, but you don't want to keep using old API version, because over time a new requests come from the business and might require using some new features.


What if the business require development with a new feature right away and your current API doesn't yet support it?


You can do it by developing a standalone class/page/component. Meaning components with the latest version that doesn't has any dependency with other components in your org (those with the lower API).


For example the ContactService class can be developed without referencing the AccountService.

public with sharing class ContactService{

    public static void manageContact(){
        for(String field : Account.getSobjectType().getDescribe().fields.getMap().keyset()){
            allFields += field + ',';
        }
    
        List<Account> accountList = Database.query('SELECT ' + allFields.removeEnd(',') + ' FROM Account Limit 10');
    
        for(Account acc : accountList){
            System.debug('Tier:: ' + acc.Tier);
        }
    }
}


In such case, note it as exception, the reason for the implementation with different version and that this code can be improved in future when you will upgrade all your other code API version.

Customize Lightning Icons in Web Components


The use of icons is very common and Salesforce provides an excellent package of icons that we can use freely.

Of course, we can find many icons on other sites or create unique icons ourselves. The disadvantage in the first one is that you usually have to check if there are license matters, and in the second requires more efforts. Therefore, as much as possible it is recommended to use the Salesforce icons.

Salesforce icons have several limitations, which sometimes make developers less likely to use them, but those can often be overcome with simple customization.


Icon Color

The icons in the utility set are by default with grey color. This can be easily changed to either green/red/yellow using the variant property.

 <div style="background-color:white;">  
   
     <!--no color-->  
     <lightning-icon icon-name="utility:new" size="small">  
     </lightning-icon>  
   
     <!--green-->  
     <lightning-icon icon-name="utility:new" size="small" variant="success">  
     </lightning-icon>  
   
     <!--yellow-->  
     <lightning-icon icon-name="utility:new" size="small" variant="warning">  
     </lightning-icon>  
   
     <!--red-->  
     <lightning-icon icon-name="utility:new" size="small" variant="error">  
     </lightning-icon>  
   
   </div>  


Result: 



If we need higher level of customization, we can set any color using css and styling hooks.

Just add any color code in the css and use it as class for the icons

 .icon-custom-light-blue{  
   --lwc-colorTextIconDefault:#99ceff;  
 }  
 .icon-custom-purple{  
   --lwc-colorTextIconDefault:purple;  
 }  


 <div style="background-color:white;">  
     <!--Custom Colors-->  
     <lightning-icon icon-name="utility:new" size="small" class="icon-custom-light-blue">  
     </lightning-icon>  
   
     <lightning-icon icon-name="utility:new" size="small" class="icon-custom-purple">  
     </lightning-icon>  
   </div>  

Result:




Icon Size

The icon have property size, that can get text values: xx-small, x-small, small, medium, or large, however the size also can be customize to have specific value using styling hooks. Similar to the colors, we can set the specific size in css and then use it as a class.

icon

 .icon-tiny{  
   --lwc-squareIconSmallBoundary:0.8rem;  
 }  
 .icon-huge{  
   --lwc-squareIconSmallBoundary:4rem;  
 }  

 <div style="background-color:white;">  
     <!--Custom size-->  
     <lightning-icon icon-name="utility:new" size="small" class="icon-tiny">  
     </lightning-icon>  
   
     <lightning-icon icon-name="utility:new" size="small" class="icon-custom-purple icon-huge">  
     </lightning-icon>  
   </div>  

Result:





Inactive Icon

Unlike button, the icons doesn't have disable property. We can hide the entire icon using template element, but in some cases it is bad user experience and we really need to disable it. To get similar result, we can easily add opacity value to the icon and change the cursor pointer.

Of course, that in addition, if the icon has onclick event we will need to halt the code in case the icon is disable.

 .icon-enable{  
   opacity: 1;  
   cursor: pointer;  
 }  
   
 .icon-disable{  
   opacity: 0.5;  
 }  

 <div style="background-color:white;">  
     <!--Enable-->  
     <lightning-icon icon-name="utility:new" size="small" class="icon-enable">  
     </lightning-icon>  
   
     <lightning-icon icon-name="utility:new" size="small" class="icon-custom-purple icon-enable">  
     </lightning-icon>  
   
     <!--Disable-->  
     <lightning-icon icon-name="utility:new" size="small" class="icon-disable">  
     </lightning-icon>  
   
     <lightning-icon icon-name="utility:new" size="small" class="icon-custom-purple icon-disable">  
     </lightning-icon>  
   </div>  

Result:




Salesforce Formula.recalculateFormulas Usage

Many Salesforce developers are not familiar with the method Formula.recalculateFormulas and possible was never needed to use it. Actually I'm developing in the Salesforce platform for years and was never needed it until recently.

The idea behind the method is that it recalculate all formula fields on the record for you without the need from you to query or changing the database.


Formula might be very complex, but to demonstrate the usage I created simple checkbox formula on account:

Consider the following code:

Account demoAcc = [	SELECT Id,Is_Account_Valid__c,Website FROM Account WHERE Website= null LIMIT 1];

//Website is empty, therefore the formula will be false
system.assertEquals(false, demoAcc.Is_Account_Valid__c); demoAcc.Website = 'www.testsite.com'; //assertion will fail, although website is now not empty. system.assertEquals(true, demoAcc.Is_Account_Valid__c);


The last assertion is failing, although the Website is populated which should change the formula to true. The formula is still false because this is the value when I query the record.

It will work if I will invoke Formula.recalculateFormulas after setting the site

Account demoAcc = [	SELECT Id,Is_Account_Valid__c,Website FROM Account WHERE Website= null LIMIT 1];

//Website is empty, therefore the formula will be false
system.assertEquals(false, demoAcc.Is_Account_Valid__c); demoAcc.Website = 'www.testsite.com'; Formula.recalculateFormulas(new List<Account>{demoAcc}); //assertion is fine as recalculateFormulas changed the formula system.assertEquals(true, demoAcc.Is_Account_Valid__c);


Important note that should take under consideration - the recalculate clear all reference fields.

Consider this code:

Account demoAcc = [	SELECT Id,Is_Account_Valid__c,Website,Owner.Name FROM Account WHERE Website= null LIMIT 1];

System.debug(demoAcc.Owner.Name);	//output: Liron Cohen

Formula.recalculateFormulas(new List<Account>{demoAcc});
System.debug(demoAcc.Owner.Name);	//output: null


The Owner.Name is null after the method invocation. This will happen for any field from reference and might be issue if you have logic based on that data.

To solve the issue, I can store the reference data and use it after the recalculate. 

For example:

Account demoAcc = [	SELECT Id,Is_Account_Valid__c,Website,Owner.Name FROM Account WHERE Website= null LIMIT 1];

User accOwner = demoAcc.Owner;

System.debug(demoAcc.Owner.Name);	//output: Liron Cohen

Formula.recalculateFormulas(new List<Account>{demoAcc});

demoAcc.Owner = accOwner;
System.debug(demoAcc.Owner.Name);	//output: Liron Cohen


Another important thing to note, is that the method actually does re-query the data, therefore it is counted as additional Soql query in the transaction limit and the records that processed are counted in the query rows limit.

If I will check the debug log from the last piece of code, I can see 2 Soql and 2 query rows. First for my query and second from the method recalculateFormulas.



Approval Process Reminders (Without Code)

I published recently open source code for setting approval process reminder alert. The code uses free app - Asynchronous Process Manager / Creator - to schedule its processing. In this post I will show alternative option for setting such alerts, without custom code, but only usage of the app.

Keep in mind:

1.The solution require few setup actions per each approval process

2.It provide less capabilities than the solution in the open source code, but should be enough for most use cases


What setup is needed?

Per each approval that we want to use will need:

  1. Date/time field that indicate how long record is pending for approval
  2. Checkbox formula that indicate if reminder should be send for the record
  3. In the approval process fields update that set/clear the date/time field


For the demo, I added approval process on opportunity therefore I created in opportunity:

-Custom date/time field: Approval Start Time

-Formula checkbox: Approval Send Reminder

        The first part calculate the time passed since the Approval Start Time (in hours) and if it is greater than 48 then the formula will be evaluated to true


In my approval process I set 2 approval steps and use 2 fields update:

    • Set Approval Start Time to Now
    • Clear Approval Start Time


What is next?

Use the app to configure a process for sending the alerts.

  • Before starting the next steps: go to Setup->Custom Metadata Types. Click Manage next to Module Standard Object Option, click edit next to record Async Template. In the Available Standard Objects add at the end 'ProcessInstance;ProcessInstanceStep;' and click Save. This settings will allow us to access those objects types in the next steps.


1.Go to tab Async Job Template and click New

2.Provide Name, set status to Live and click Save



3.Click the button Set Actions. This process will have 5 steps, so we can click Add Action button*5 and provide the action names + type


Now lets fill the detail for each step:

Step1- find opportunities record based on the new checkbox field. We should retrieve all
opportunities were Approval Send Reminder is true.
Click button Set Action Params next to the first step, select Related Object as Opportunity,
click + icon to add filter and compare the Approval Send Reminder equal to true (checked)
Click button Close

Step 2 - search Process Instance related to the opportunities.
Click button Set Action Params next to the second step. Select the Related Object as Process
Instance, add filter, select the field Target Object Id equal, click the green filter icon,
choose filter by Find Opportunities for Alert and select the Opportunity Id


Step 3 - select the Related Object as Process Instance Step, add filter Process
Instance Id equal, click the green filter icon , select Filter By Find Related Process
Instance and select the field Process Instance Id

Step 4 - we will create Log Message records in order to send an alerts, which is part of
the package functionalities.
Fill the input
Data Source: Action
Action Source: Find Related Process Instance Steps
Object to Insert: Log Message

In the Field Setup section, select the following fields and set their values as follow:



Last step simply update the opportunity Approval Start Time to now, in order to reset the
counter.

Click Save button above the action list.


Now lets schedule the process.
Click button Create Async Job
Potentially- provide email to get summary email when the process complete
Set Time to Run
Check the Is Repeated Option
Repeated Type: Minutes
Repeated Interval: [Minutes per your needs]

Click Next



Video for the configuration of the Async Job Template:



Tip. If you would like to use email template for the alert, just modify the forth step in the
Async Job Template. Instead of setting the fields Subject and Message Email set the following
fields (Email Template Id should be your email template Id):








Using Custom Milestone Process in Salesforce


I formerly worked for a company that had a complicated, multi-steps approval process. One of the issues was that the process would frequently come to a halt at some point, and the approver would postpone their approval for days, if not weeks. The causes for the delay can vary, but the solution we implemented was pretty straightforward: we establish deadlines for each stage of the approval process, warn the approver several hours beforehand with email reminder, and if he does not approve, send him and his direct manager another reminder.

Amazingly, the alerts has dramatically reduced the approval times.

It appears that we frequently need due dates and phases in our process (breaking a complex task into steps, sounds familiar?), and occasionally we need enforcement actions to remind us of our tasks. The milestone concept and their functionalities include all of this.


The application Customized Timeline Process was designed exactly for that kind of tasks. Building processes per the organization need with few button clicks.

The application support setting milestone steps for any data type in the system (standard/custom) as well as automation actions for enforcing the times. In addition, the app provides reports to analyze the results and identify where there is room for improved performance.

As an example lets look at a milestone process on the Account.

I set first step as: Set Required fields, which as the name indicate it require to fill some essentials data on the account.
Per the configuration the user should fill the fields Rating, Industry and Website in order to complete this step and it should be done within 1 day.



In addition, I set an alert 
action to be sent to the account manager 1 hour before the due date.


Continue with step 2: Create First Opportunity 
(expected to be done within 3 days)

And later Step 3 and 4: Schedule a Demo Meeting and Close the Opportunity, will eventually the result with the following configuration:


After activating the process, any time new account will be created the application will automatically generate its related steps, automatically complete each step and execute the relate actions, as can be seen in the short video







Salesforce Time Logger



I saw similar question is some cases - we want to allow the user to report working hours directly in Salesforce.

Each implementation usually has unique specification, so I will share here the basic concept that can be used as basic and then customized/extended.


General idea is a custom component where user can report their hours + and optional component for manager to assign users with total hours they allowed to report. 

Therefore, it can be use in either way:

  • Placing Time Log component in record page and setting the property 'use assignment' to false,  allowing users to report hours on the record without limitation.
  • Placing Time Log component in the record page + Time Log Assignment (expose it for relevant users) and set 'use assignment' to true. This way, users can report hours only if they were assigned to.


Notice, we can add in the object Time Log lookup field for the object you want to links the reported hours and this will automatically populated. This way can use the standard components to display logs related list.

in the record page, without the lookup field only the the field Related_Record_Id will be set which is just an text field.


Rollups?

Common request with such functionality is to have rollup from the time logs to the parent object. For such request will need to set the lookup field in Time Log as suggest above.

Might consider the following points:

-In case it will be used only for 1 object, can simply set the relation to the object as master/detail and use build-in rollup summary fields.

-In case it will be used for few objects and there are several rollups needed might replicate the Time Log object per each case (Time Log Opportunity, Time Log Case...) and still use the mater/detail relation and the rollup fields.

-In other cases, were we ending with the lookup relation field, will need to handle the rollup calculations with customization.


Full code can be found in git:

https://github.com/liron50/shared-code/tree/main/timelog

Running Test Classes From Apex Code


Salesforce provides a few objects for working with test classes directly from apex code.

It provides the ability to schedule test runs with a list of test classes and the ability to query the test result. Seems the main part which is not supported is the code coverage. The result contains only information regarding success/failure and errors in case of failure. For the code coverage, we will need to use another API (for example, tooling API). 

Basically, to set up a test run, all we need to do is to insert ApexTestQueueItem records. Each record indicate a test class that should be running. Creating several items in the same transaction will link them all under the same test.


In the following demo, I tried to keep it simple. Therefore, I'm using native apex without an API. I'm using a web components that allow me to select a list of test classes, set specific intervals and schedule it to run at a specific time.

Clicking the Run Test button set up a job to run which first creates the ApexTestQueueItem items and then set a second job to check the result in 5 minutes, as the tests run asynchrounsly. 

When the job running, it first checks if all the related ApexTestQueueItem items were completed. If it does, then it queries the result and reports any failure that was found during the test. If not all tests are completed, it set job to check it again in 5 minutes. 

  • 5 minutes might be too low value if I'm running all tests, but for the demo purpose it is fine.


Another issue that you need to consider: the code using the standard object ApexClass to get a list of classes, but it cannot indicate if a specific class is a test class. In the code, I'm getting the class content and check if it contains the text @istest, but it is not 100% correct.


Also note that for the solution I'm a free app: Asynchronous Process Manager / Creator, which allow to easily set and monitor background jobs and it provides some other core components that are used and saves some efforts.


Can view the full code in git


Retire of Permission on Profiles

If you are working as a Salesforce admin/developer you've probably heard somewhere that Salesforce is planning to make a significant cha...