Tag: Error Message

  • Chat Transcripts summaries using OpenAI

    Chat Transcripts summaries using OpenAI

    It is often necessary to reread the Chat Transcript with the customer to identify a problem and its solution, but the dialog can be very long and contain irrelevant information. AI comes to the rescue. It will easily provide you with the most important points of dialogue without unnecessary information.

    In this article we will use OpenAI, triggers, and Apex classes.

    Good to know
    Before we start, I recommend familiarizing yourself with the OpenAI limits by clicking the link.

    Main steps:

    1. Create an account on OpenAI.com and generate an ApiKey
    2. Set up Named Credentials
    3. Add external credential principal access to the profile
    4. Create a text field on the Chat Transcript object, where the compressed information of the dialogue with the customer will be stored
    5. Create the main logic using Apex Trigger and Apex Classes

    Generating ApiKey

    After creating an OpenAI account, we need to generate an ApiKey. Go to Personal and select View API keys. Click on the Create new secret key button and enter the name of your key. Copy and save the generated key somewhere, we will need it later.

    API keys are used for authenticating a calling program to another API – typically to confirm a project is authorized to connect.

    Set up Named Credentials

    A named credential specifies the URL of a callout endpoint and its required authentication parameters in one definition. To simplify the setup of authenticated callouts, specify a named credential as the callout endpoint.

    Salesforce manages all authentication for callouts that specify a named credential as the callout endpoint. You can also skip remote site settings, which are otherwise required for callouts to external sites, for the site defined in the named credential.

    In the setup Quick find box find Named Credentials, choose External Credentials tab and click New button.

    Enter external credential Label, Name and Authentication Protocol and click Save.

    Click New button near the Principal section and enter:

    • Parameter Name: Token
    • Sequence Number: 1.

    Add Authentication Parameters and enter:

    • Parameter Name: Token
    • Value: your OpenAI generated ApiKey and click Save

    Click New button near the Custom Headers section and enter:
    Name: Authorization
    Value: {!$Credential.Your_Named_Credential_API_Name.Your_Principal_Name}
    Sequence Number: 1

    Click Save.

    dont miss out iconDon’t forget to check out: How to Send Any Salesforce Notifications to Slack Channels: A Complete Guide

    Go to the Named Credentials and click New. Enter Named credentials:
    Label: OpenAI API
    Name: OpenAI_API
    URL: https://api.openai.com
    Select your external credential from the picklist, uncheck Generate Authorization Header checkbox, check Allow Formulas in HTTP Header checkbox and click Save.

    Click New button near the Custom Headers section and enter:

    • Name: Content-Type
    • Value: application/json
    • Sequence Number: 1

    Click Save.

    Add external credential principal access to the profile

    Go to your profile and add external credential principal access.

    Chat Transcript Field Creation

    To store main information of a dialogue with a client, we can use a text field specially created for this on the Chat Transcript object.

    In the setup Object Manager find the Chat Transcript object, click Fields & Relationships tab and click New button. Select text Data Type, fulfill all necessary fields, choose layout for displaying the field and click Save.

    Main logic creation

    A chat transcript is a record of a chat between a customer and an agent. Salesforce automatically creates a transcript for each chat session.

    Requirements

    After the agent completes the chat, display the main idea of the dialogue in the Summary field (we created it earlier).

    Important
    When you’re using Omni-Channel routing, the chat transcript is created when the chat’s requested by a visitor. When a chat ends successfully by a customer or an agent, the chat transcript is updated with Body field as soon as the agent closes the chat window and any related tabs.

    Solution

    Let’s create an Apex Trigger for Chat Transcript object.

    Then let’s create a trigger handler class.

    Since we are using an after update trigger and plan to update the summary field with the Body field, we need to add a check for the Body field to avoid trigger recursion. The Body field should be changed and can’t be blank.

    dont miss out iconCheck out another amazing blog here by Vimera: How to make Error Handling in the Batches much Easier?

    In updateTranscriptSummary() we execute batch with a chunk of 100 records to avoid limits.

    Now let’s create an Apex Batch with the main logic.
    This article is prepared by our Salesforce developer Dmitry Mitkevich. To continue reading, please visit our website.
  • How to make Error Handling in the Batches much Easier?

    How to make Error Handling in the Batches much Easier?

    Have you ever faced such situation, when your batch handles loads of data, and suddenly one of chunks has failed, and to understand the cause of an error, you have to write customer error handlers to catch the error? And what if your org has dozens of various batches with different logic?

    Well, Salesforce has a solution for this.

    Any batch can implement the interface called Database.RaisesPlatformEvents which will wrap up your batch with a standard handler.

    First, you need to ensure that your batch is implementing Database.RaisesPlatformEvents interface.

    After that, if any unhandled error happens in your batch, the platform event called BatchApexErrorEvent will be created.

    This event according to documentation has next fields:

    • AsyncApexJobId – The AsyncApexJob record for the batch Apex job that fired this event.
    • DoesExceedJobScopeMaxLength – True if the JobScope field is truncated due to the message exceeding the character limit.
    • EventUuid – A universally unique identifier (UUID) that identifies a platform event message. This field is available in API version 52.0 and later.
    • ExceptionType – The Apex exception type name. Internal platform errors are represented as the System.UnexpectedException type.
    • JobScope – The Record IDs that are in scope if the event was fired from the execute() method of a batch job. If the batch job uses custom iterators instead of sObjects, JobScope is the toString() representation of the iterable objects. The maximum length is 40000 characters.
    • Message – The exception message text. The maximum length is 5000 characters.
    • Phase – The phase of the batch job when it encountered an error (start, execute, finish).
    • ReplayId – Represents an ID value that is populated by the system and refers to the position of the event in the event stream. Replay ID values aren’t guaranteed to be contiguous for consecutive events. A subscriber can store a replay ID value and use it on resubscription to retrieve missed events that are within the retention window.
    • RequestId – The unique ID of the batch job that fired the event. Event monitoring customers can use this information to correlate the error with logging information.
    • StackTrace – The Apex stacktrace of the exception, if available. The maximum length is 5000 characters.

    Once an event is created the next step is to catch and handle that event. There is a way to do it quite simple.

    dont miss out iconDon’t forget to check out: Data Manipulation and Error Handling in Salesforce

    Create the platform event triggered flow.

    Than choose BatchApexErrorEvent platform event to handle.

    Now $Record that is being passed to flow is BatchApexErrorEvent event that contains data about the batch error and the batch itself.

    Now in this flow you can create a custom object (that should be created before), to store all error data, or send email about the batch error, or even fix records that have failed to proceed.

    This event can be handled by a flow, apex trigger, processes and pub/sub API and streaming API.

    As you can see RaisesPlatformEvents interface can make error handling in the batches much easier. You will receive complete information about your batch error.

    dont miss out iconCheck out another amazing blog here by Vimera: Marketing Cloud Account Engagement (Pardot) Use Cases

    This article was originally published on the Vimera’s website.

  • Apex Trigger Scenarios – Part 1

    Apex Trigger Scenarios – Part 1

    Some Important Questions

    Write a trigger to throw error when user deactivates the account record and if that account has atleast one opportunity with the stage not equal to closed won or closed lost.

    trigger PreventAccountDeactivation on Account(before update) { 
         // Loop through the list of accounts being updated 
         for (Account acc: Trigger.new) { 
              // Check if the account's IsActive field is being set to false (i.e. deactivated) 
              if (acc.IsActive == false && Trigger.oldMap.get(acc.Id).IsActive == true) { 
                   // Query for opportunities related to this account where the stage is not "Closed Won" or "Closed Lost" List 
                   < Opportunity > opps = [ SELECT Id FROM Opportunity WHERE AccountId =: acc.Id AND StageName NOT IN('Closed Won', 'Closed Lost') ]; 
                   // If there are any such opportunities, throw an error if (!opps.isEmpty()) { 
                        acc.addError('Cannot deactivate this account because it has opportunities with a stage other than "Closed Won" or "Closed Lost".'); 
                        } 
              }
         } 
    }

    Employee record’s Status cannot be changed to “Terminated” if there is/are no Employee Review records added to it

    trigger PreventTerminatedStatus on Employee__c (before update) { 
         // Loop through the list of employees being updated 
         for (Employee__c emp : Trigger.new) { 
              // Check if the employee's Status field is being set to "Terminated" 
              if (emp.Status__c == 'Terminated' && Trigger.oldMap.get(emp.Id).Status__c != 'Terminated') { 
                   // Query for Employee Review records related to this employee List<Employee_Review__c> reviews = [ SELECT Id FROM Employee_Review__c WHERE Employee__c = :emp.Id ]; 
                   // If there are no Employee Review records, throw an error if (reviews.isEmpty()) { 
                   emp.addError('Cannot set status to "Terminated" because there are no Employee Review records added to this employee.'); 
                   } 
              } 
         } 
    }

    dont miss out iconDon’t forget to check out: What are Apex Triggers? | All You Need to Know

    There will be three objects User, Contact, and Account. and these objects have one custom field name is isActive. So, if I will uncheck the IsActive Checkbox from the Account then also uncheck the isActive checkbox of the related user of that account and all the contact associate with the account

    trigger DeactivateRelatedRecords on Account (before update) { 
         // Loop through the list of accounts being updated 
         for (Account acc : Trigger.new) { 
              // Check if the account's IsActive field is being set to false (i.e. deactivated) 
              if (acc.IsActive == false && Trigger.oldMap.get(acc.Id).IsActive == true) { 
                   // Query for related users and contacts List<User> users = [ SELECT Id, IsActive FROM User WHERE AccountId = :acc.Id ]; 
                   List<Contact> contacts = [ SELECT Id, IsActive FROM Contact WHERE AccountId = :acc.Id ]; 
                   // Set the IsActive field to false for all related users and contacts 
                   for (User user : users) { user.IsActive = false; } 
                   for (Contact contact : contacts) { contact.IsActive = false; } 
                   // Update the related users and contacts update users; update contacts; 
                   } 
         }
    }

    What is the Difference Between Context variables and Static variables in triggers?

    Context Variables:

    • Context variables are variables that provide information about the context in which a trigger is executed.
    • They are system-provided variables and cannot be explicitly defined or modified by the developer.
    • Context variables are available only within the trigger execution context and are not accessible outside of it.
    • Examples of context variables include Trigger.new, Trigger.old, Trigger.newMap, Trigger.oldMap, and Trigger.isBefore.
    • These variables provide access to the records being processed by the trigger and allow developers to perform operations based on the trigger context.

    Static Variables:

    • Static variables, on the other hand, are variables that are explicitly defined and shared among all instances of a class.
    • They are defined using the “static” keyword and are associated with the class itself, rather than with specific instances of the class.
    • Static variables retain their values across multiple trigger invocations and can be accessed and modified by any method or trigger within the class.
    • Unlike context variables, static variables are not tied to the trigger execution context and can be used outside of the trigger.
    • Static variables are often used to store values that need to be shared across multiple trigger events or to maintain state information.

    What are the Different types of Context variables in triggers?

    Trigger Context Variables are:

     

    isExecuting Returns true if the current context for the Apex code is a trigger, not a Visualforce page, a Web service, or an executeanonymous() API call.
    isInsert Returns true if this trigger was fired due to an insert operation, from the Salesforce user interface, Apex, or the API.
    isUpdate Returns true if this trigger was fired due to an update operation, from the Salesforce user interface, Apex, or the API.
    isDelete Returns true if this trigger was fired due to a delete operation, from the Salesforce user interface, Apex, or the API.
    isBefore Returns true if this trigger was fired before any record was saved.
    isAfter Returns true if this trigger was fired after all records were saved.
    isUndelete Returns true if this trigger was fired after a record is recovered from the Recycle Bin. This recovery can occur after an undelete operation from the Salesforce user interface, Apex, or the API.
    new Returns a list of the new versions of the sObject records. This sObject list is only available in insert, update, and undelete triggers, and the records can only be modified in before triggers.
    newMap A map of IDs to the new versions of the sObject records. This map is only available in before update, after insert, after update, and after undelete triggers.
    old Returns a list of the old versions of the sObject records. This sObject list is only available in update and delete triggers.
    oldMap A map of IDs to the old versions of the sObject records. This map is only available in update and delete triggers.
    operationType Returns an enum of type System.TriggerOperation corresponding to the current operation. Possible values of the System.TriggerOperation enum are: BEFORE_INSERT, BEFORE_UPDATE, BEFORE_DELETE,AFTER_INSERT, AFTER_UPDATE, AFTER_DELETE, and AFTER_UNDELETE. If you vary your programming logic based on different trigger types, consider using the switch statement with different permutations of unique trigger execution enum states.
    size The total number of records in a trigger invocation, both old and new.

    When ever the Account is created with the Industry field as “IT” then create a contact for the account, use the Contact “Lastname” value from the Account name and the contact phone from account phone.

    trigger CreateContactOnAccountCreation on Account (before insert) { 
    // Loop through the list of accounts being inserted
    for (Account acc : Trigger.new) {
    // Check if the account's Industry field is set to "IT" if (acc.Industry == 'IT') {
    // Create a new contact record Contact contact = new Contact();
    // Set the Lastname field to the account name contact.LastName = acc.Name;
    // Set the Phone field to the account phone contact.Phone = acc.Phone;
    // Set the AccountId field to the ID of the account being inserted contact.AccountId = acc.Id;
    // Add the contact to the list of records to be inserted insert contact;
    }
    }
    }

    dont miss out iconCheck out another amazing blog by Aman here: Apex Trigger Scenarios | All You Need to Know

    Write a trigger on the account to count all the accounts with their respective countries

    trigger CountAccountsByCountry on Account (after insert, after update, after delete, after undelete) { 
    // Query for all the distinct countries where accounts are located Set<String> countries = new Set<String>();
    for (Account acc : [SELECT BillingCountry FROM Account]) {
    countries.add(acc.BillingCountry); }
    // Create a map to store the counts for each country Map<String, Integer> counts = new Map<String, Integer>();
    // Initialize the counts to 0 for each country for (String country : countries) { counts.put(country, 0);
    }
    // Query for all the accounts and update the counts
    for (Account acc : [SELECT Id, BillingCountry FROM Account]) {
    counts.put(acc.BillingCountry, counts.get(acc.BillingCountry) + 1); }
    // Update the custom field on the Account object with the counts for each country List<Account> accountsToUpdate = new List<Account>();
    for (String country : counts.keySet()) {
    Account acc = new Account(); acc.BillingCountry = country; acc.Accounts_in_Country__c = counts.get(country); accountsToUpdate.add(acc); }
    update accountsToUpdate;
    }

    How to check the old value in the field using a trigger?

    trigger MyTrigger on MyObject__c (before update) {
        for (MyObject__c obj : Trigger.old) {
            // Check the old value of a field
            if (obj.FieldName__c != Trigger.oldMap.get(obj.Id).FieldName__c) {
                // Field value has changed
                // Perform desired actions here
            }
        }
    }

    1000 records are being processed through a Batch to update any object like Account. Write code to maintain how many records failed to be updated.

    trigger AccountTrigger on Account (before update) { 
    // Declare a variable to store the count of failed records Integer failedRecordCount = 0;
    // Loop through the records in the trigger context for (Account account : Trigger.new) {
    // Check if the record is in an error state if (account.isValid() == false) {
    // If the record is in an error state, increment the failed record count failedRecordCount++;
    }
    }
    // Save the failed record count in a custom field on the object for (Account account : Trigger.new) {
    account.Failed_Record_Count__c = failedRecordCount;
    }
    }

    Make a field on account object “No of Total Contact”. Write a trigger to count the total no of contact associated with the particular account when the contact is inserted or deleted.

    trigger ContactTrigger on Contact (after insert, after delete) { 
    // Get the list of account IDs for the inserted or deleted contacts Set<Id> accountIds = new Set<Id>();
    for (Contact contact : Trigger.new) {
    accountIds.add(contact.AccountId);
    }
    // Query for the accounts with the matching IDs List<Account> accounts = [ SELECT Id, No_of_Total_Contacts__c FROM Account WHERE Id IN :accountIds ];
    // Loop through the accounts and update the "No of Total Contacts" field
    for (Account account : accounts) {
    account.No_of_Total_Contacts__c = [ SELECT COUNT() FROM Contact WHERE AccountId = :account.Id ];
    }
    // Update the accounts with the new contact count update accounts;
    }

    Account has 10 opportunity links to them. The owner changed the email field to any one of the one opportunity It will update all the sibling’s opportunities with the same account.

    trigger AccountTrigger on Account (before update) { 
    // Get the list of account IDs that have been updated Set<Id> accountIds = new Set<Id>();
    for (Account account : Trigger.new) {
    accountIds.add(account.Id);
    }
    // Query for the opportunities with matching account IDs
    List<Opportunity> opportunities = [ SELECT Id, AccountId, Email__c FROM Opportunity WHERE AccountId IN :accountIds ];
    // Loop through the opportunities and update the email field
    for (Opportunity opportunity : opportunities) {
    // Find the corresponding account for the opportunity Account
    account = Trigger.oldMap.get(opportunity.AccountId);
    // Update the email field on the opportunity opportunity.Email__c = account.Email;
    }
    // Update the opportunities with the new email field value update opportunities;
    }

    When the user is deactivated then it’s related Accounts and opportunity will automatically assign to its manager.

    trigger UserTrigger on User (before update) { 
    // Get the list of user IDs that have been updated Set<Id> userIds = new Set<Id>();
    for (User user : Trigger.new) {
    userIds.add(user.Id);
    }
    // Query for the users with the matching IDs List<User>
    users = [ SELECT Id, IsActive, ManagerId FROM User WHERE Id IN :userIds ];
    // Create a map of user IDs to managers Map<Id, Id> userManagerMap = new Map<Id, Id>();
    for (User user : users) {
    userManagerMap.put(user.Id, user.ManagerId);
    }
    // Query for the accounts and opportunities with matching owner IDs List<Account> accounts = [ SELECT Id, OwnerId FROM Account WHERE OwnerId IN :userIds ];
    List<Opportunity> opportunities = [ SELECT Id, OwnerId FROM Opportunity WHERE OwnerId IN :userIds ];
    // Loop through the accounts and opportunities and update the owner field
    for (Account account : accounts) {
    account.OwnerId = userManagerMap.get(account.OwnerId);
    }
    for (Opportunity opportunity : opportunities) {
    opportunity.OwnerId = userManagerMap.get(opportunity.OwnerId);
    }
    // Update the accounts and opportunities with the new owner field value update accounts; update opportunities;
    }

     

  • All You Need to Know About Recursive Triggers in Salesforce

    All You Need to Know About Recursive Triggers in Salesforce

    What are Recursive Triggers?

    In Salesforce, a Recursive Trigger refers to a situation where a trigger on an object causes another trigger to fire on the same object. This can create a loop that repeats indefinitely, resulting in an error message or even causing the system to crash. In this blog post, we will discuss the causes and consequences of Recursive Triggers in Salesforce, as well as strategies to prevent them.

    Causes of Recursive Triggers

    Recursive Triggers can occur when a trigger on an object performs an operation that triggers another trigger on the same object. For example, consider a scenario where a Trigger on the Account object updates the related Contact records. If the Contact object also has a Trigger that updates the related Account record, a Recursive Trigger is created.

    Another common cause of Recursive Triggers is when a Trigger performs an update on the same record that caused the Trigger to fire in the first place. This can create a loop that repeats indefinitely, as the Trigger continues to fire on the updated record.

    dont miss out iconDon’t forget to check out: Learn About the Governor Limits in Salesforce

    Consequences of Recursive Triggers 

    Recursive Triggers can cause a variety of issues in Salesforce, including: 

    • Excessive API calls: Each time a Trigger fires, it consumes API calls. If a Recursive Trigger continues to fire repeatedly, it can quickly consume all available API calls and cause other integrations to fail. 
    • Performance issues: Recursive Triggers can cause significant performance issues, especially if they involve complex logic or large data sets. This can result in slow page load times, timeouts, and other user experience issues. 
    • Data inconsistency: If a Recursive Trigger creates a loop that updates the same record repeatedly, it can lead to data inconsistencies and errors. 

    Preventing Recursive Triggers

    Fortunately, there are several strategies that developers can use to prevent Recursive Triggers in Salesforce. Here are some best practices to follow: 

    • Use a static variable to control Trigger recursion: By using a static variable, you can track whether a Trigger has already fired and prevent it from firing again. Here’s an example: 
    public class AccountTriggerHandler { 
        private static Boolean isExecuting = false; 
        public static void onBeforeUpdate(List<Account> newAccounts, Map<Id, Account> oldMap) { 
            if (!isExecuting) { 
                isExecuting = true; 
                // Perform Trigger logic here 
                isExecuting = false; 
            } 
        } 
    }
    • Limit Trigger depth: To prevent Recursive Triggers, you can limit the number of times a Trigger can fire on a single object. For example, you can use a static variable to track the depth of a Trigger and prevent it from firing after a certain number of iterations. 
    • Use Trigger frameworks: Trigger frameworks like TriggerHandler or TriggerFactory can help prevent Recursive Triggers by providing a standardized way to handle Trigger logic. 
    • Test Trigger logic thoroughly: It’s important to test Trigger logic thoroughly to ensure that it doesn’t create Recursive Triggers. This includes unit testing as well as testing in a sandbox or developer org. 

    dont miss out iconCheck out another amazing blog here: Why Salesforce Apex Trigger is Unique?

    Conclusion

    Recursive Triggers can cause a variety of issues in Salesforce, including performance issues, data inconsistency, and API limits. Fortunately, by following best practices like using static variables, limiting Trigger depth, and using Trigger frameworks, developers can prevent Recursive Triggers and ensure that their Trigger logic runs smoothly.

  • An Introduction to Screen Flow in Salesforce in 2023

    An Introduction to Screen Flow in Salesforce in 2023

    Screen flows are those in which there is user interaction and the user sees a user interface (UI) where they can either enter data or choose records. As an illustration, imagine that you intended to use a screen flow to establish an account record, requiring the user to fill out all the necessary data before the account is created when they hit the submit button. 

    The benefits of a guided screen flow are numerous. The number of validation criteria required for data entry might be decreased. It gives us a logical data entry flow that can alter dynamically depending on the values entered. We can guide a user through a business process and avoid using massive top-to-bottom screens by creating a nice screen flow. 

    Difference between Screen Flow and Autolaunched Flow

    Since screen flow consists of screens, steps, choices, or dynamic options, user interaction is required. Auto-launched Flow, on the other hand, doesn’t call for human involvement. This flow type does not support screens or options. 

    One of the many different types of Flows you can utilize in Salesforce to improve user experience is the Screen Flow. For instance, you can design a user interface (UI) to gather data on a single page and store it on many objects in the background, or you can display a wizard-like UI to lead people through the transaction process. 

    dont miss out iconDon’t forget to check out: Introducing Screen Flow in Salesforce

    The ability to accomplish all of this without writing a single line of code is what makes the screen flow appealing. utilizing tools for declarative point-and-click. I see you’re paying attention now. A Lightning page, Lightning Community, or Quick Action can all include Screen Flow as an add-on.

    The screen’s header and footer are under your control. Additionally, you can regulate screen switching by activating or removing the “Next or Finish” and “Previous” buttons. Additionally, users have the option to “Pause” the flow and restart it at a later time. 

    Various standard input components are included in the screen element of Flow, including Address, Call Script, Checkbox, Currency, Date & Time, Picklists, Display Image, Email, File Upload, Long Text Area, Lookup, Multi-Select Picklist, Name, Number, Password, Phone, Radio Buttons, Slider, Text, Toggle, URL, etc. 

    Additionally, a typical “Display Text” component is used to show information to users running the Flow. Additionally, there are more Screen components available on the AppExchange (wow!).

    Making the Flow screen dynamic using Conditional visibility is among its best features. The screen will alter dynamically while running depending on the condition and logic you define. Control when a component shows. The user’s input can be verified on a Flow screen, and if necessary, an error message can be displayed to direct the user to correct their input. 

    dont miss out iconCheck out another amazing blog here: What is the Flow Builder In Salesforce in 2023?

    Only a few of the aforementioned features and components will be covered in this guide. Within the next 45 minutes, after reading this guide, you will discover how to:

    Establish a screen flow 

    • Save & Turn Screen Flow On 
    • Increase the Lightning Page’s Screen Flow. 
    • Run a screen flow test. 
    • Flow From Quick Action Launch 
  • What are Validation Rules in Salesforce? | All You Need to Know

    What are Validation Rules in Salesforce? | All You Need to Know

    The main purpose of using the Salesforce Validation rule verifies that the data a user enters in a record meets the standards you specify before the user can save the record. In case it doesn’t, the validation rule automatically shows an error message with a short explanation of what was entered incorrectly, this restricts the user to prevent from saving changes with invalid data. By having such rules, you can avoid incorrect values in the field. 

    Usually, these come in the form of required field sets that need to fill out with a particular field change. 

    How Do Validation Rules Work?

    Validation Rules evaluate or trigger every single time there is an attempt to save the record for a particular field for which the validation rule has been written. The formulas contain one or more criteria that should be met in order to pass validation and save the record.

    Simply put, the validation rules check whether a specific field (or multiple fields) corresponds to the mentioned criteria. If the data is evaluated to be true, the record gets saved. If not, the rule displays an error message, specifying the mistakes. This means that unless the user modifies the fields to match the criteria, they won’t be able to go through verification when a new record is created or when changes to an existing one are trying to be saved.

    dont miss out iconDon’t forget to check out: Defining Validation Rules in Salesforce

    Steps To Create Validation Rules

    1. Select your Object (Standard/ Custom). Go to the “Setup” section, from the Gear icon, then Object Manager from the tab, and choose your object from the detailed object list for which you want to create validation rules.
    2. Once you select your object, the object menu preview pane opens up, scroll down to the last and click on Validation Rule.
    3. Once the Validation Rule page opens up Click on New, and it will open the Object Validation Rule page.
    4. Name the Rule, Tick the “Active” checkbox, and in the “Description” field give a brief explanation of what the rule should do.
    5. Creating the Error Condition Formula. Moving on to the “Error Condition Formula Section”, we all need to create a formula that will identify the validation rule criteria. It’ll be made up of the chosen “Function” (on the right, you can see the box, containing a large selection of function categories), the selected field (via the “Insert Field”), and the operator (that’s indicated via the “Insert Operator” button).
    6. Once you specify your Logic for Validating Field in Error Condition formula Section by using various Functions sections, Insert operator Section (for various Arithmetic tools). Click on check syntax.
    7. The “Check syntax” Button will help you to evaluate your code logic and specify your “No Error Syntax” or “Error Syntax with Description” by evaluating your Formula.
    8. Defining the Error Message & its Location, The Error Message is a mandatory field when setting up a validation rule. Importantly, this message needs to state what was done wrong, i.e., where the user made a mistake, explaining in short how to make the fix  
    9. Specify the Error location, Mention the location of your Error message by choosing the radio button (either on the top of the page or beside the field for which the validation rule is made). 

    dont miss out iconCheck out another amazing blog by Saurabh here: Introduction to the Scratch Org | All You Need to Know

    Finally, click on “Save” button to save the rule. Test the rule by creating a record and check whether the “Validation Rule” work as expected. 

  • What are Validation Rules in Salesforce in 2023?

    What are Validation Rules in Salesforce in 2023?

    In this blog, we will explore the importance of validation rules and how to create them in Salesforce. 

    What are Validation Rules in Salesforce? 

    Validation rules are a set of criteria that are used to ensure that data entered into Salesforce meets certain standards. They can be used to prevent users from entering incorrect or incomplete data, as well as to ensure that data is consistent across different fields and objects. 

    Validation rules can be applied to any object in Salesforce, including standard and custom objects. They can be used to check for a variety of conditions, such as: 

    • Required fields: Ensuring that certain fields are filled in before a record can be saved. 
    • Data format: Checking that data entered into fields follows a certain format, such as a valid email address or phone number. 
    • Data range: Ensuring that data entered falls within a specific range or value, such as a date range or a maximum or minimum number. 
    • Field dependencies: Ensuring that data entered in one field is dependent on data entered in another field. 
    • Business logic: Enforcing business rules, such as preventing the creation of duplicate records. 

    dont miss out iconDon’t forget to check out: Create Sharing Rules Unit in Salesforce – Learn Here

    Why are Validation Rules Important? 

    Validation rules are important because they help ensure the accuracy and consistency of data in Salesforce. By preventing users from entering incorrect or incomplete data, validation rules can help improve the quality of data in the system. This can lead to more accurate reporting and analytics, as well as improved decision-making. 

    In addition, validation rules can help prevent data inconsistencies and errors that can arise when data is entered by multiple users or from different sources. By enforcing data standards across the organization, validation rules can help ensure that data is consistent and reliable. 

    How to Create Validation Rules in Salesforce? 

    Creating a validation rule in Salesforce involves the following steps: 

    Step 1: Navigate to the Object Manager 

    Navigate to the Object Manager and select the object on which you want to create a validation rule. 

    Step 2: Click on Validation Rules 

    Under the object, click on the Validation Rules tab and then click the new button to create a new validation rule. 

    Step 3: Define the Rule Criteria 

    Define the criteria that will trigger the validation rule. This can be done using a formula or by selecting pre-defined options from the dropdown menus. 

    Step 4: Define the Error Message 

    Define the error message that will be displayed to users when the validation rule is triggered. This message should explain why the record cannot be saved and provide guidance on how to correct the error. 

    Step 5: Activate the Validation Rule 

    Once the validation rule is created, activate it by selecting the Active checkbox. 

    dont miss out iconCheck out another amazing blog by Nikhil here: Sharing Settings in Salesforce | The Ultimate Guide

    Conclusion 

    Validation rules are an important tool for ensuring the accuracy and consistency of data in Salesforce. By enforcing data standards across the organization, validation rules can help improve the quality of data, leading to more accurate reporting and decision-making. With a few simple steps, you can create validation rules in Salesforce that will help your organization maintain high-quality data and achieve better results. 

  • File Upload in Lightning Web Component (LWC) | All You Need to Know

    File Upload in Lightning Web Component (LWC) | All You Need to Know

    User can upload multiple files in LWC using lightning-file upload. Due to the fact that file uploads are always associated with a specific record, the record-id attribute is required. The attachments related list on the record detail page and the Owned by Me filter in Files Home are where you can find uploaded files. Despite the fact that Salesforce is compatible with all file types, you can restrict the file types by utilising the accept attribute.  

    The file picker in the Lightning Design System is where the lightning-file-upload component gets its styling. 

    File Upload Example  

    FileUploadLWC.html 

    <template> 
        <lightning-card title="LWC File Upload Example" icon-name="custom:custom19"> 
            <lightning-file-upload 
                label="Attach receipt" 
                name="fileUploader" 
                accept={acceptedFormats} 
                record-id={recordId} 
                onuploadfinished={handleUploadFinished} 
                multiple> 
        </lightning-file-upload> 
        </lightning-card> 
    </template>

    dont miss out iconDon’t forget to check out: Learn the Basics of LWC in No Time! | Salesforce Lightning Web Components

    FileUploadLWC.js 

    import { LightningElement, api } from 'lwc'; 
    import {ShowToastEvent} from 'lightning/platformShowToastEvent'; 
    export default class FileUploadLWC extends LightningElement { 
        @api recordId; 
        get acceptedFormats() { 
            return ['.pdf', '.png','.jpg','.jpeg']; 
        } 
        handleUploadFinished(event) { 
            // Get the list of uploaded files 
            const uploadedFiles = event.detail.files; 
            let uploadedFileNames = ''; 
            for(let i = 0; i < uploadedFiles.length; i++) { 
                uploadedFileNames += uploadedFiles[i].name + ', '; 
            } 
            this.dispatchEvent( 
                new ShowToastEvent({ 
                    title: 'Success', 
                    message: uploadedFiles.length + ' Files uploaded Successfully: ' + uploadedFileNames, 
                    variant: 'success', 
                }), 
            ); 
        } 
    }

    FileUploadLWC.xml 

    <?xml version="1.0" encoding="UTF-8"?> 
    <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"> 
        <apiVersion>48.0</apiVersion> 
        <isExposed>true</isExposed> 
        <targets>  
            <target>lightning__AppPage</target> 
            <target>lightning__RecordPage</target> 
            <target>lightning__HomePage</target> 
        </targets> 
    </LightningComponentBundle>

    dont miss out iconCheck out another amazing blog by Ashutosh here: What is an Enhanced Domain in Salesforce in 2023?

    How to get Clicked Record from a List of Records?

    • If you want to add files on a list of records (for example, Query opportunities and have file upload option in front of each record), so you can use lightning-input type = file and assign each record an id using data-id in html. 
    • Data-id will be used in js file to assign a record-id from where the file upload option is clicked using event.target.id 

    File Upload Limit 

    You can upload up to 10 files at once unless your Salesforce admin changed the default upload limit. Per organisation, a minimum of 1 file and a maximum of 25 files may be uploaded simultaneously. Up to 2 GB of data can be uploaded. The maximum file sizes and accepted file formats in Communities are governed by the guidelines issued by community file moderation. By default, guests are unable to upload files. One can enable the org preference. Allow website visitors to upload files. 

  • Validation Rules in Salesforce | All You Need to Know

    Validation Rules in Salesforce | All You Need to Know

    Validation rules in Salesforce are used to enforce data quality by ensuring that data entered into Salesforce meets certain standards. They are used to validate data before it is saved to the database, and can prevent incorrect or incomplete data from being saved. 

    Validation rules are defined as a set of conditions that must be met before data can be saved. When a record is saved and the conditions specified in the validation rule are not met, an error message is displayed to the user. This message can be customized to provide specific information about what needs to be corrected in order to save the data. 

    There are several types of validation rules that can be created in Salesforce, including: 

    1. Field-Level Validation: Validates the data entered into a specific field, such as checking that a date is in the correct format, or that a field contains a value greater than zero. 
    2. Record-Level Validation: Validates the data entered into multiple fields, such as checking that the combination of values in two fields is unique. 
    3. Cross-Object Validation: Validates the data entered into fields across multiple objects, such as checking that the sum of values in two fields on separate objects is equal. 

    dont miss out iconDon’t forget to check out: Create Sharing Rules Unit in Salesforce – Learn Here

    To create a validation rule in Salesforce, you must have the “Customize Application” permission. The process involves navigating to the object where you want to create the validation rule, clicking on the “Validation Rules” button, and then defining the conditions that must be met for the rule to be considered valid. You can also specify the error message that will be displayed to the user if the rule is violated. 

    It is important to note that validation rules can have a significant impact on the user experience, so it is important to consider the impact on your users before creating a new rule. Additionally, it is recommended to test validation rules thoroughly before deploying them to a production environment. 

    In conclusion, validation rules are a powerful tool in Salesforce that can help to ensure data quality and consistency. When used effectively, they can help to improve the accuracy and completeness of data in your Salesforce instance. 

    Validation rules are also useful for enforcing business rules and processes within an organization. For example, a validation rule could be created to ensure that all opportunities have a probability of closing set to a value greater than 50% before the opportunity can be marked as “Closed Won.” This ensures that sales representatives are only marking opportunities as won if they are confident that the sale will close. 

    dont miss out iconCheck out another amazing blog by Pranjal: Wrapper Classes in Salesforce | Here’s What You Need to Know

    Additionally, validation rules can be used to enforce compliance with regulations and standards. For example, a validation rule could be created to ensure that all contact information entered into Salesforce meets privacy regulations, such as checking that a contact’s age is over 18 before their information can be saved. 

    Validation rules can also be combined with other Salesforce features, such as workflows, to automate certain processes. For example, a validation rule could be used to trigger a workflow that sends a notification to a manager if a record does not meet the specified conditions. 

    It is important to keep validation rules simple and straightforward, as complex validation rules can be difficult for users to understand and may lead to frustration. When creating validation rules, it is recommended to involve a cross-functional team, including representatives from sales, marketing, and IT, to ensure that the rules align with the needs and processes of the organization. 

    In conclusion, validation rules are an important tool for enforcing data quality, business rules, and compliance in Salesforce. They can help to improve the accuracy and consistency of data, automate processes, and ensure that organizations are following best practices. 

  • Best Practices for Salesforce Lightning Web Components (LWC)

    Best Practices for Salesforce Lightning Web Components (LWC)

    Always Name Carefully

    1. Always name variables, methods, and components carefully. 
    2. Do not start a property name with ‘on’, ‘aria’, or ‘data’. 
    3. Do not use reserved keywords like ‘slot’, ‘part’, or ‘is’. 

    Naming Convention

    1. Try to name your files in the below format
      • Component Name – camelCase
      • Component Class Name – PascalCase
      • Component reference – kebab-case 
      • HTML Attribute Name – kebab-case 

    dont miss out iconDon’t forget to check out: Assign Permission Set at the User Creation Made Simple: What You Need to Know | Salesforce Guide

     Use Spread Operator for adding additional attributes in data returned from Apex

    1. We frequently need to add extra properties to the data returned from apex according to the requirement. 

     Be mindful of Case Sensitivity

    1. Lightning Web Components are case-sensitive.  
    2. Be very careful while writing your writing code. 

     Instead of Expressions, Use Getters

    1. Use a JavaScript getter, to compute a value for a property. 
    2. Getters are more powerful than expressions because these are JavaScript functions and also enable unit testing, which reduces bugs and increases the fun.   

     Do not forget to assign a key to each

    1. While using iteration in LWC, do not forget to assign the key attribute within the scope of the iteration. 
    2. Otherwise, you will get the below error: ” Elements within iterators must have a unique, computed key value.

     Use an iterator to apply special rendering to the first and last elements of list

    1. If you want to apply a special style or rendering to the first and last element of the list, use iterator instead of for:each. 
    2. Iterator has two more attributes: first and last. 

    Pass only primitive data in custom event

    1. As one of the best practices, pass only primitive data types in custom events. 
    2. JavaScript passes all data types by reference except for primitive data types. 
    3. So, any listener can mutate the actual object which is not good practice.   
    4. If at all we need to pass an object, we need to copy the data to a new object before sending it so that it does not get changed by any of the listeners. 

    Use LDS whenever possible

    1. Instead of making apex calls to get the data, try to use LDS. 
    2. It requires no apex code and can perform Create, Read, Update, Delete operations on a single record 
    3. It also takes care of the sharing rules and field-level security. 

    Avoid using hardcoding, use custom labels

    1. Similar to apex, avoid using hardcoding in LWC.  
    2. Keep the text inside a custom label and configure it as and when required without making any changes to existing code. 

    dont miss out iconDon’t forget to check out: Assign Permission Set at the User Creation Made Simple: What You Need to Know | Salesforce Guide

    Include error handling in the code logic

    1. We should consider the error scenario as well and notify the user with a user-friendly error message 
    2. For this, we can make use of toast messages to show high-level detail to users on what went wrong. 

    Specify fields instead of layout in lightning-record-form

    1. To improve performance, specify specific fields instead of layout in lightning-record-form 
    2. If we specify the layout, the component must handle receiving every field that is assigned to the layout for the context user. 
  • Defining Validation Rules in Salesforce

    Defining Validation Rules in Salesforce

    Validation Rule

    With this post, we will learn about Validation Rule, which are criteria defined to validate the data entered by the user when creating or manipulating the records. This event occurs after the save button has been clicked. This can contain the formula or expression that validates the data and returns ‘true’ or ‘false’. It can also return an error message associated with that particular validation rule so that the user can see it when he enters invalid data. A validation rule can be created for an object, a field, a campaign member, or a case milestone. 

    Steps: 

    Follow the step to create a validation rule for the object. 

    1. Goto SetUp>>Customize>>Account(Any Object). 
    2. From the left sidebar click the validation rule. 
    3. Click New. 
    4. Enter the Name of the rule. 
    5. In the Error Condition Formula section define your criteria to validate the data. 
    6. To check the formula or expression for error click on Check Syntax. 
    7. In Error Message section define your message and position which will appear when the user enters the wrong data. 
    8. Finally, Save it. 

    dont miss out iconDon’t forget to check out: Create Sharing Rules Unit in Salesforce – Learn Here

    Example: 

    Now we are going to write a validation rule for contact objects which fires when contact is saved. This rule validates whether a contact’s age is more than 18 years or not. This will cause an error when contact’s age is less than 18. 

    1. Goto SetUp>>Customize>>Contact. 
    2. From the left sidebar click the validation rule. 
    3. Click New. 
    4. Enter the Name of the rule i.e. Verify_Age 
    5. In the Error Condition, Formula section define your criteria to validate the data. i.e  Year ( Birthdate) > 1999 
    6. To check the formula or expression for error click on Check Syntax. 
    7. In the Error Message section define your message and position which will appear when the user enters the wrong data. i.e. Contact must be more than or equal to 18 years 
    8. Finally, Save it.