How to avoid updating certain field values in Salesforce using trigger?

In the below example, if the account type is Customer - Direct and if the user tries to update any fields other than Industry and Description, it will throw an error.

Field Set:



Sample Code:


  1. trigger AccountTrigger on Account ( before update ) {  
  2.   
  3.     Map < String, Schema.SObjectField > accountFieldsMap = new Map < String, Schema.SObjectField >();  
  4.     Set < String > setFieldsToIgnore = new Set < String >();  
  5.       
  6.     for ( Schema.FieldSetMember f :  SObjectType.Account.FieldSets.Fields_To_Excluded_for_Update.getFields() )     
  7.         setFieldsToIgnore.add( f.getFieldPath() );    
  8.       
  9.     for ( Schema.SObjectField objField : Schema.SObjectType.Account.fields.getMap().values() ) {  
  10.       
  11.         Schema.DescribeFieldResult F = objField.getDescribe();  
  12.         String strFieldName = F.getName();  
  13.           
  14.         if ( F.isUpdateable() && !setFieldsToIgnore.contains( strFieldName ) )  
  15.             accountFieldsMap.put( strFieldName, objField );  
  16.           
  17.     }  
  18.   
  19.     for ( Account objAcc : trigger.new ) {  
  20.       
  21.         Account oldAcc = trigger.oldMap.get( objAcc.Id );  
  22.       
  23.         if ( objAcc.Type == 'Customer - Direct' && oldAcc.Type == 'Customer - Direct' ) {  
  24.               
  25.             List < String > fieldNames = new List < String >();  
  26.             for ( String objField : accountFieldsMap.keySet() ) {  
  27.                   
  28.                 if ( objAcc.get( objField ) != oldAcc.get( objField ) )  
  29.                     fieldNames.add( accountFieldsMap.get( objField ).getDescribe().getLabel() );  
  30.               
  31.             }  
  32.               
  33.             if ( fieldNames.size() > 0 )  
  34.                 objAcc.addError( 'You cannot edit ' + String.join( fieldNames, ', ' ) );  
  35.           
  36.         }  
  37.           
  38.     }  
  39.   
  40. }  

Output:


How to get content from lightning:inputRichText without HTML Tags?

Sample Code:

Lightning Component:


  1. <aura:component implements = "force:appHostable">  
  2.       
  3.     <aura:attribute name="myVal" type="String" />  
  4.       
  5.     <div class="slds-box slds-theme_default">  
  6.           
  7.         <lightning:inputRichText value = "{!v.myVal}"/>  
  8.         <lightning:button variant = "brand" label = "Show" onclick = "{! c.handleClick }"/>  
  9.           
  10.     </div>  
  11.       
  12. </aura:component>  

Lightning Component Controller:


  1. ({  
  2.       
  3.     handleClick : function(component, event, helper) {  
  4.           
  5.         var tempVal = component.get("v.myVal");  
  6.         var tempDivElement = document.createElement("div");  
  7.         tempDivElement.innerHTML = tempVal;  
  8.         alert( "With HTML Tags " + tempVal );  
  9.         tempVal = tempDivElement.textContent;  
  10.         alert( "Without HTML Tags " + tempVal );  
  11.           
  12.     }  
  13.       
  14. })  

Output:






INVALID_QUERY_LOCATOR, Unable to find query cursor data for this QueryLocator

When a query has to return more data, Salesforce uses Query Locators. In order to understand more about this

http://www.infallibletechie.com/2018/10/what-is-query-locator-in-salesforce.html

Reasons may be below for the exception

1. Too much data for a single query. Try to limit the data.

2. You've exceeded your allowance of having max 5 queryLocators open.

3. You've exceeded 10 minute inactivity timeout of a queryLocator.

Salesforce adding hyphen (-) to the Opportunity Name

This is Standard Salesforce functionality. By default, Salesforce allows you to add the name which starts with Account Name -. So that user can edit that name and use some other name. Generally people use Account Name-Opportunity Name.


Check this for more information.

https://help.salesforce.com/articleView?id=000193659&type=1

How to subscribe to Salesforce Change Data Capture from MuleSoft?

To know about Change Data Capture, check the below link

https://www.infallibletechie.com/2019/05/change-data-capture-in-salesforce.html

Salesforce Change Data Capture:



MuleSoft Flow:



Subscribe Channel Configuration:



Transform Message Configuration:



Logger Configuration:



Output:



Change Data Capture in Salesforce

A CDC event, or change event, is a notification that Salesforce sends when a change to a Salesforce record occurs as part of a create, update, delete, or undelete operation. The notification includes all new and changed fields, and header fields that contain information about the change. For example, header fields indicate the type of change that triggered the event and the origin of the change. Change events support all custom objects and a subset of standard objects.

When to use Change Data Capture
Use change events to:

1. Receive notifications of Salesforce record changes, including create, update, delete, and undelete operations.
2. Capture field changes for all records.
3. Get broad access to all data regardless of sharing rules.
4. Get information about the change in the event header, such as the origin of the change, which allows ignoring changes that your client generates.
5. Perform data updates using transaction boundaries.
6. Use a versioned event schema.
7. Subscribe to mass changes in a scalable way.
8. Get access to retained events for up to three days.

Subscription Channels
Use the subscription channel that corresponds to the change notifications you want to receive. The channel name is case-sensitive.

All Change Events
/data/ChangeEvents

A Standard Object
/data/<Standard_Object_Name>ChangeEvent

For example, the channel to subscribe to change events for Account records is:
/data/AccountChangeEvent

A Custom Object
/data/<Custom_Object_Name>__ChangeEvent

For example, the channel to subscribe to change events for Employee__c custom object records is:
/data/Employee__ChangeEvent

How to set it up

1. Go to Change Data Capture.


2. Select and add objects from Available to Selected Entities.


System Mode and User Mode in Salesforce

Trigger runs in System mode. If triggers calls an apex class with sharing keyword, then record level access will be considered.

Validation Rule runs in System mode.

Auto Response Rule runs in System mode.

Assignment Rule runs in System mode.

Workflow Rule runs in System mode.

Escalation Rule runs in System mode.

Formula, Rollup Summary runs in System mode.

Process Builder runs in System mode.

Custom Button runs in System mode.

Visual Workflow or flow runs in User mode.
If flow is called from Process Builder, then runs in System mode.
If flow is called from Workflow, then runs in System mode.
If flow is called from Apex, then runs in (depends on with or without sharing of apex class).
If flow is called from Custom Button, then runs in System mode.
If flow is embed in Visualforce, then runs in VFP context.
If flow is called from REST API, then runs in System mode.

Approval Process runs in System mode.

Publisher Action runs in System mode.

InvocableMethod
If this is called from flow, then runs in User mode.
If this is called from Process Builder (does it depends on with or without sharing is specified on that Class), then runs in System mode.
if this is called from REST API, then runs in (depends on with or without sharing of the class).

Test method with System.runAs() runs in User mode.
Test method without System.runAs() runs in System mode.

Visualforce Page (StandardController) runs in User mode.
Visualforce Page (StandardController with extension) runs in System mode.
Visualforce Page (Custom Controller) - Based on the sharing keyword usage in the apex class.
Visualforce Component runs in depends on Visualforce page where it is used.

Macros runs in System mode.

Annonymous Apex runs in User mode.

Chatter in Apex runs in User mode.

Email Service runs in User mode.

All types of Jobs runs in System mode.

Apex Webservices (SOAP API and REST API) runs in System mode. 

How to ensure Field Level Security in SOQL in Salesforce?

Use the WITH SECURITY_ENFORCED clause to enable field and object level security permissions checking for SOQL SELECT queries in Apex code, including subqueries and cross-object relationships.

If any fields or objects referenced in the SOQL SELECT query using WITH SECURITY_ENFORCED are inaccessible to the user, an exception is thrown, and no data is returned.

Example
If field access for either LastName or Description is hidden, this query throws an exception indicating insufficient permissions.
view sourceprint?

List<Account> act1 = [SELECT Id, (SELECT LastName FROM Contacts),
   (SELECT Description FROM Opportunities)
   FROM Account WITH SECURITY_ENFORCED]

The WITH SECURITY_ENFORCED clause is only available in Apex. Using WITH SECURITY_ENFORCED in Apex classes or triggers with an API version earlier than 45.0 is not recommended.

How to override New button in Salesforce Lightning Experience?

Use lightning:actionOverride in the aura:component to override standard actions in Salesforce Lightning Experience.

Sample Code:

  1. <aura:component implements="lightning:actionOverride" access="global" >  
  2.       
  3.     <b>You cannot create records from here!!!</b>  
  4.       
  5. </aura:component>  

Action Override:


Output:


Phone No and Email fields in Task and Event objects in Salesforce

Phone No and Email fields in Task and Event objects in Salesforce are not editable and are auto populated from the associated contact or lead record.

These are special fields as they pull the information of Phone and Email from either Contact or Lead.

Contains the phone number of the contact or lead related to the task. This field is filled in with the value from the related contact or lead record.



Activity Related To in Salesforce

Activities can be related to many objects Accounts, Opportunties, Contacts, leads, Custom Objects, etc.

Related To shows objects where Allow Activity is enabled and the user have at least read access to the object.


TIMEVALUE formula in Salesforce

TIMEVALUE function returns the time in GMT.

When the user select Date/Time field in Salesforce, they select it in their timezone. But, Salesforce saves that in GMT.


Usage of OrgLimit Class and OrgLimits Class

OrgLimit Class
The System.OrgLimit class contains methods that return the name, current value, and maximum limit for an instance.

getName() - Returns the limit’s name.
getValue() - Returns the limit usage value.
getLimit() - Returns the maximum allowed limit value.

OrgLimits Class
The System.OrgLimits class contains methods that return a list of all org limits or a map of all org limit names and values.

getAll() - Returns a list of OrgLimit instances.
getMap() - Returns a map of all OrgLimit instances with the limit name as key.

Sample Code:


  1. for ( OrgLimit o : OrgLimits.getAll() ) {  
  2.       
  3.     system.debug( o.getName() + ' - ' + o.getValue() + ' - ' + o.getLimit() );  
  4.       
  5. }  

Output:



Error: Function ISCHANGED may not be used in this type of formula

Usually this error happens when the workflow evaluation criteria is not "when a record is: created, and every time it’s edited".

ISCHANGED  function is available only in:

1. Assignment rules
2. Validation rules
3. Field updates
4. Workflow rules if the evaluation criteria is set to Evaluate the rule when a record is: created, and every time it’s edited .
5. Formula criteria for executing actions in Process Builder.
6. This function returns FALSE when evaluating any field on a newly created record.
7. If a text field was previously blank, this function returns TRUE when it contains any value.
8. For number, percent, or currency fields, this function returns TRUE when:
a. The field was blank and now contains any value
b. The field was zero and now is blank
c. The field was zero and now contains any other value

How to find the Limits in Salesforce Org real quick?

Run the below code in Anonymous window.

Sample Code:

  1. for ( OrgLimit o : OrgLimits.getAll() ) {  
  2.       
  3.     system.debug( o.getName() + ' - ' + o.getValue() + ' - ' + o.getLimit() );  
  4.       
  5. }  

Get the debug log to find the limits.


(OR)

Run the below code in Anonymous window.

Sample Code:

  1. Http h = new Http();  
  2. HttpRequest req = new HttpRequest();  
  3. req.setEndpoint( Url.getOrgDomainUrl().toExternalForm() + '/services/data/v44.0/limits' );  
  4. req.setMethod('GET');  
  5. req.setHeader( 'Authorization''Bearer ' + UserInfo.getSessionId() );  
  6. HttpResponse res = h.send(req);  
  7. system.debug( 'Limits are ' + res.getBody() );  

Get the debug log to find the limits.

Salesforce Summer '19 Release Quick Summary

Monitor Custom Metadata Type Use in System Overview

Understand your current custom metadata type usage pattern to plan for future custom metadata type work. You can now view custom metadata type usage in System Overview. You can get information about the number of custom metadata types and the size of the custom metadata type records used in your org.



Easily Insert Files When Composing a Case-Related Email
Agents can attach files to an email more easily. Files related to a case or attached to an email are collected under Related Files in the file selector. You can add multiple files at once. And the selector prevents you from adding duplicates.



Access Lightning Experience from Safari on iPad Devices (Beta)
Give your users the ability to run the full desktop version of Lightning Experience on their iPad device when they’re away from their desktop or laptop.

Power Up Your Related Lists with Enhanced Related Lists
Take your related lists to the next level. With Enhanced Related Lists, you can show up to 10 columns, resize and sort your columns, perform mass actions, and wrap text.

Keep Record Context When Switching from Salesforce Classic to Lightning Experience
When you switch from Salesforce Classic to Lightning Experience, you land on the same page in Lightning Experience, if it exists. If the same page doesn’t exist in Lightning Experience, you are redirected to your default landing page, which is determined by the org default or your customizations.

Zoom Through Related Lists with Quick Filters
Use quick filters in your related lists to find the data that you’re looking for. Related list quick filters are different from regular list view filters in that they aren’t saved, persist only throughout your current session, and can’t be shared.


Search Picklist Fields in List Views
You don’t have to manually pick through your list views to find the picklist values you’re looking for. List view search now includes picklists in your query results. Dependent picklists and picklists with translated values aren’t searchable.

See More in Item Menus on the Navigation Bar
We increased the number of recent items shown in item menus from three to five. We also made some styling enhancements, including bold section names and separators, to make it easier to tell the different sections apart.

The Lightning Experience Header Is Hidden When You Print from Your Browser
All you want is what’s on the page. The Lightning Experience header, including the search box and navigation bar, is no longer included when you print from your browser.

Current Print View(Shows Search bar)



Summer '19 Print View


Choose from Two Record View Options
Now you have two record page view default options. Choose between the current view—now called Grouped view—and the new Full view. Full view displays all details and related lists on the same page. If you’re transitioning to Lightning Experience, this view is similar to Salesforce Classic.

Make Long-Running Callouts with Continuations
Use the Continuation class in Apex to make a long-running request to an external web service from an Aura component or a Lightning web component. Process the response in a callback method. An asynchronous callout made with a continuation doesn’t count toward the Apex limit of 10 synchronous requests that last longer than five seconds. Therefore, you can make more long-running callouts and integrate your component with a complex back-end API.

Enforce Field-Level Security in Apex (Pilot)
Apex has a new security feature for field-level data protection, which is accessed through the Security and SObjectAccessDecision classes. To ensure secure processing in Apex in the context of the current user’s read, create, or update operation, use the stripInaccessible method. Based on the field-level security of the current user, this method can be used to strip the fields from query results that the user can’t access. The method can also be used to remove inaccessible fields from sObjects before a DML operation to avoid exceptions and to sanitize sObjects that have been deserialized from an untrusted source.

  1. List<Opportunity> opportunities = new List<Opportunity>{  
  2.     new Opportunity(Name='Opportunity1'),  
  3.     new Opportunity(Name='Opportunity2', Probability=95)  
  4. };  
  5.   
  6. // Strip fields that are not creatable  
  7. SObjectAccessDecision decision = Security.stripInaccessible(  
  8.     AccessType.CREATABLE,  
  9.     opportunities);  
  10.   
  11. // Print stripped records  
  12. for (SObject strippedOpportunity : decision.getRecords()) {  
  13.     System.debug(strippedOpportunity);  
  14. }  
  15.   
  16. // print modified indexes  
  17. System.debug(decision.getModifiedIndexes());  
  18.   
  19. // Print removed fields  
  20. System.debug(decision.getRemovedFields());  
  21.   
  22. //System.debug Output  
  23. // DEBUG|Opportunity:{Name=Opportunity1}  
  24. // DEBUG|Opportunity:{Name=Opportunity2}  
  25. // DEBUG|{1}  
  26. // DEBUG|{Opportunity={Probability}}  

Fire Platform Events from Batch Apex Classes (Generally Available)
Batch Apex classes can fire platform events when an error or exception is encountered. A batch Apex class declaration must be using API version 44.0 or later to implement the Database.RaisesPlatformEvents interface and fire a platform event. A platform event record now includes the phase of the batch job (start, execute, or finish) when the error was encountered. The start and finish methods of the Database.Batchable interface now fire platform events on error (which they didn’t do in the beta release).

public with sharing class YourSampleBatchJob implements Database.Batchable<SObject>,
   Database.RaisesPlatformEvents{
   // class implementation
}

Receive Streaming Events in Your Lightning Web Component
In Winter ’19, we introduced the lightning:empApi Aura component for subscribing to event streaming channels in your Aura components. Now you can do the same in your Lightning web components using the lightning/empApi module.

Process Change Event Messages in Apex Triggers
With Apex change event triggers, you can now process change event messages on the Lightning Platform. Change event triggers run asynchronously after the database transaction is completed. Perform resource-intensive business logic asynchronously in the change event trigger and keep transaction-based logic in the Apex object trigger. By decoupling the processing of changes, change event triggers can help reduce transaction processing time.

Work with More Custom Objects in Your Org
We raised the total hard limit for custom objects in an org to 2,500 so that you can install more custom objects from packages. Each Salesforce edition has a specific limit on the number of custom objects that you can create in your org. Beyond the edition limit, the hard limit governs how many custom objects you can install from managed packages, such as apps publicly posted on AppExchange. The new 2,500 limit includes the maximum number of custom objects created and installed in your org.

Path: Celebrate Sales Milestones
Help your teams celebrate their successes. Toss some virtual confetti when reps reach a designated path stage, for example, winning an opportunity. You can choose the frequency, such as always for those hard-won victories or only sometimes for daily occurrences. Celebrations don’t work on the status Converted on leads.



Custom Object Access Settings Default to Private
When you create custom objects, the external access level now defaults to Private if you’ve enabled external org-wide defaults. Previously, the external access level defaulted to Public Read/Write.

Merge Cases into a Single Record (Beta)
If you have duplicate cases or cases that you want to merge into a single case, you can now merge two or three cases into one master record. When you merge cases, the master record is updated with your chosen field values. Most related lists, feed items, and child records are merged into the master record. The master record keeps the Chatter feeds, your values for read-only and hidden fields (except Created Date and Created By), related items, and security.

Get Notified When Reports Conditions Are Met
Don’t wait to find out when an important aggregate in your Salesforce report reaches a meaningful threshold. When a change affects a report that you rely on, report subscribers can receive the updated information right away. For instance, set conditions to send email when average case age is greater than one day, or opportunity count rises above 100. Choose whether the email contains a summary of the conditions that were met or a summary plus the whole report.


Evaluate Each Record in Reports with Row-Level Formulas (Beta)
Answering business questions sometimes means making a calculation on every row in a report. With row-level formulas, you don't need to export report data to a spreadsheet or ask an admin to create a one-off custom formula field. Instead, write a row-level formula directly in the Lightning report builder.



Find Records Faster with Search
Wading through an entire report to find just the records you’re interested in can be time-consuming. The report table search makes its entrance so that you spend less time looking for the information you need.


Find Existing Letterheads in a New Location in Salesforce Classic
Looking for the letterheads that you created in Salesforce Classic? They’re still there in Setup, under the renamed menu option Classic Letterheads.