Tag Archives: Apex

Handle Trigger and Validation Rule Error in Lightning Component

Sometimes we can have a requirement to display validation rule error or apex trigger error messages, on save of record in Lightning Component. We can handle those errors from apex controller and can throw messages to Lightning Component. In lightning response object though the state value comes as ERROR but the message in the error object always says ‘Internal Server Error”. Here is an example to handle the Trigger and Validation Rule Error in apex controller to show error messages in Lightning Component.

In below example I’ve used Lead object FirstName, LastName, Email & Company Field in lightning component to create record. And I’ve created a validation rule and a trigger validation on Lead object.

1. Validation rule for Company field (Company cannot be Test Company).

2. In below Trigger I’m checking if FirstName field value is “Test” then it will throw error.

trigger LeadTrigger on Lead (before insert, before update) {
    
    for(Lead obj :Trigger.new){
        if(obj.FirstName == 'Test'){
            obj.FirstName.addError('First name cannot be test');
        }
    }
}

Apex Controller:

public class SampleAuraController {
    
    @AuraEnabled
    Public static void createLead(Lead objLead){
        String msg = '';
        try{
            //Insert Lead Record
            insert objLead; 
            
        }catch(DmlException e){
            //Any type of Validation Rule error message, Required field missing error message, Trigger error message etc..
            //we can get from DmlException
            
            //Get All DML Messages
            for (Integer i = 0; i < e.getNumDml(); i++) {
                //Get Validation Rule & Trigger Error Messages
                msg =+ e.getDmlMessage(i) +  '\n' ;
            }
            //throw DML exception message
            throw new AuraHandledException(msg);
            
        }catch(Exception e){
            //throw all other exception message
            throw new AuraHandledException(e.getMessage());
        }
        finally {
        }
    } 
}

Lightning Component:

<!--Sample.cmp--> 
<aura:component controller="SampleAuraController" implements="flexipage:availableForAllPageTypes,force:appHostable">
    
    <!--Declare Attributes-->
    <aura:attribute name="isSpinner" type="boolean" default="false"/>
    <aura:attribute name="objLead" type="Lead" default="{'sobjectType':'Lead', 
                                                        'FirstName': '',
                                                        'LastName': '',
                                                        'Email': '', 
                                                        'Company': ''}"/>
    
    
    <!--Component Start--> 
    <div class="slds-m-around--xx-large">
        <div class="container-fluid">
            <div class="form-group">
                <lightning:input name="fname" type="text" maxlength="50" required="true" label="First Name" value="{!v.objLead.FirstName}" />
            </div>
            <div class="form-group">
                <lightning:input name="lname" type="text" maxlength="50" required="true" label="Last Name" value="{!v.objLead.LastName}" />
            </div>
            <div class="form-group">
                <lightning:input name="emailId" type="email" maxlength="100" required="true" label="Email" value="{!v.objLead.Email}" />
            </div>
            <div class="form-group">
                <lightning:input name="company" type="text" maxlength="50" required="true" label="Company" value="{!v.objLead.Company}" />
            </div>
        </div>
        <br/>
        <lightning:button variant="brand" label="Submit" onclick="{!c.handleLeadSave}" />        
        <lightning:button label="Cancel" onclick="{!c.handleCancel}"/>        
    </div>
    <!--Component End-->
</aura:component>

Lightning JS Controller:

({    
    //Handle Lead Save
    handleLeadSave : function(component, event, helper) {
        var objLead = component.get("v.objLead");
        var action = component.get("c.createLead");
        action.setParams({
            objLead : objLead
        });
        action.setCallback(this,function(a){
            var state = a.getState();
            if(state === "SUCCESS"){
                alert('Record is Created Successfully');
            } else if(state === "ERROR"){
                var errors = action.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        alert(errors[0].message);
                    }
                }
            }else if (status === "INCOMPLETE") {
                alert('No response from server or client is offline.');
            }
        });       
        $A.enqueueAction(action);
    }
})

Output:

Trigger Error Message:

Validation Rule Error Message:

Salesforce Apex Built-In Exceptions

Exception Description
AsyncException Any problem with an asynchronous operation, such as failing to enqueue an asynchronous call.
BigObjectException Any problem with big object records, such as connection timeouts during attempts to access or insert big object records.
CalloutException Any problem with a Web service operation, such as failing to make a callout to an external system.
DmlException Any problem with a DML statement, such as an insert statement missing a required field on a record.
EmailException Any problem with email, such as failure to deliver.
ExternalObjectException Any problem with external object records, such as connection timeouts during attempts to access the data that’s stored on external systems.
InvalidParameterValueException An invalid parameter was supplied for a method or any problem with a URL used with Visualforce pages.
LimitException A governor limit has been exceeded. This exception can’t be caught.
JSONException Any problem with JSON serialization and deserialization operations.
ListException Any problem with a list, such as attempting to access an index that is out of bounds.
MathException Any problem with a mathematical operation, such as dividing by zero.
NoAccessException Any problem with unauthorized access, such as trying to access an sObject that the current user does not have access to. This exception is used with Visualforce pages.
NoDataFoundException Any problem with data that does not exist, such as trying to access an sObject that has been deleted. This exception is used with Visualforce pages.
NoSuchElementException This exception is thrown if you try to access items that are outside the bounds of a list. This exception is used by the Iterator next method. For example, if iterator.hasNext() == false and you call iterator.next(), this exception is thrown. This exception is also used by the Apex Flex Queue methods and is thrown if you attempt to access a job at an invalid position in the flex queue.
NullPointerException Any problem with dereferencing null.
QueryException Any problem with SOQL queries, such as assigning a query that returns no records or more than one record to a singleton sObject variable.
RequiredFeatureMissing A Chatter feature is required for code that has been deployed to an organization that does not have Chatter enabled.
SearchException Any problem with SOSL queries executed with SOAP API search() call, for example, when the searchString parameter contains fewer than two characters.
SecurityException Any problem with static methods in the Crypto utility class.
SerializationException Any problem with the serialization of data. This exception is used with Visualforce pages.
SObjectException Any problem with sObject records, such as attempting to change a field in an update statement that can only be changed during insert.
StringException Any problem with Strings, such as a String that is exceeding your heap size.
TypeException Any problem with type conversions, such as attempting to convert the String ‘a’ to an Integer using the valueOf method.
VisualforceException Any problem with a Visualforce page.
XmlException Any problem with the XmlStream classes, such as failing to read or write XML.

Salesforce Apex Switch Statement

From Summer ’18 Release Apex now supports switch statement, that tests whether an expression matches one of several values and branches accordingly.

Syntax:

switch on expression {
    when value1 {		// when block 1
        // code block 1
    }	
    when value2 {		// when block 2
        // code block 2
    }
    when value3 {		// when block 3
        // code block 3
    }
    when else {		  // when else block, optional
        // code block 4
    }
}

Example:

for(Integer i=1; i<=5; i++){
    Switch on i {
        when 1,2{
            System.debug('case 1 and 2');
        }
        when 5{
            System.debug('case 5');
        }
        when else{
            System.debug('case 3 and 4');
        }
    }
 }

The switch statement evaluates the expression and executes the code block for the matching when value. If no value matches, the code block for the when else block is executed. If there isn’t a when else block, no action is taken.

Iterate Map List Values in Lightning Component

Apex Class:

public class SampleAuraController {
    
    @AuraEnabled
    Public static Map<string, List<string>> getMap(){ 
        Map<String, List<string>> mapObj = new Map<String, List<string>>();
        List<string> fruits = new List<String>{'Apple', 'Orange', 'Banana', 'Grapes'};
		List<string> vegetables = new List<String>{'Cabbage', 'Carrot', 'Potato', 'Tomato'};
		mapObj.put('Fruits', fruits);
        mapObj.put('Vegetables', vegetables);  
        return mapObj;
    }
}

Lightning Component:

<aura:component controller="SampleAuraController">
    <aura:attribute name="mapValues" type="object" />	
    <div class="slds-m-around_xx-large">
        <div class="slds-box slds-theme_default">
            <lightning:button label="Iterate Map" onclick="{!c.getMapValues}"/>
            <aura:iteration items="{!v.mapValues}"  var="mapKey" indexVar="key">  
                <strong><p>{!mapKey.key}</p></strong>
                <aura:iteration items="{!mapKey.value}" var="mapValue">
                    <p>{!mapValue}</p>
                </aura:iteration>
            </aura:iteration>
        </div>
    </div>
</aura:component>

Lightning Component JS Controller:

({
    getMapValues : function(component, event, helper) {
        var action = component.get("c.getMap");
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS"){
                var result = response.getReturnValue();
                var arrayMapKeys = [];
                for(var key in result){
                    arrayMapKeys.push({key: key, value: result[key]});
                }
                component.set("v.mapValues", arrayMapKeys);
            }
        });
        $A.enqueueAction(action);
    }
})

Output:

Apex String Methods to Determine Character Types

isAlpha() : This string method will return true, if the string contain only characters.

//Return true
String s1 = 'Biswajeet';
Boolean b1 = s1.isAlpha();
System.assertEquals(true, b1);

//Return false
String s2 = 'Biswajeet Samal';
Boolean b2 = s2.isAlpha();
System.assertEquals(false, b2);

//Return false
String s3 = 'Biswajeet1234';
Boolean b3 = s3.isAlpha();
System.assertEquals(false, b3);

isAlphaSpace() : This string method will return true, if the string contain alphabet and white spaces.

//Return true
String s1 = 'Biswajeet';
Boolean b1 = s1.isAlphaSpace();
System.assertEquals(true, b1);

//Return true
String s2 = 'Biswajeet Samal';
Boolean b2 = s2.isAlphaSpace();
System.assertEquals(true, b2);

//Return false
String s3 = 'Biswajeet1234';
Boolean b3 = s3.isAlphaSpace();
System.assertEquals(false, b3);

isAlphanumeric() : This string method will return true, if the string contain alphabet, numbers.

//Return true
String s1 = 'Biswajeet';
Boolean b1 = s1.isAlphaNumeric();
System.assertEquals(true, b1);

//Return true
String s2 = 'Biswajeet1234';
Boolean b2 = s2.isAlphaNumeric();
System.assertEquals(true, b2);

//Return false
String s3 = 'Biswajeet 1234';
Boolean b3 = s3.isAlphaNumeric();
System.assertEquals(false, b3);

isAlphanumericSpace() : This string method will return true, if the string contain alphabet, numbers and white spaces.

//Return true
String s1 = 'Biswajeet Samal';
Boolean b1 = s1.isAlphanumericSpace();
System.assertEquals(true, b1);

//Return true
String s2 = 'Biswajeet 1234';
Boolean b2 = s2.isAlphanumericSpace();
System.assertEquals(true, b2);

//Return false
String s3 = 'Biswajeet $$';
Boolean b3 = s3.isAlphanumericSpace();
System.assertEquals(false, b3);

isNumeric() : This string method will return true, if the string contain numbers only.

//Return true
String s1 = '12345';
Boolean b1 = s1.isNumeric();
System.assertEquals(true, b1);

//Return false
String s2 = '12.22';
Boolean b2 = s2.isNumeric();
System.assertEquals(false, b2);

//Return false
String s3 = 'Biswajeet1234';
Boolean b3 = s3.isNumeric();
System.assertEquals(false, b3);

isNumericSpace() : This string method will return true, if the string contain numbers with spaces.

//Return true
String s1 = '1 2 3 4 5';
Boolean b1 = s1.isNumericSpace();
System.assertEquals(true, b1);

//Return true
String s2 = '12.22';
Boolean b2 = s2.isNumericSpace();
System.assertEquals(false, b2);

//Return false
String s3 = 'Biswajeet 1234';
Boolean b3 = s3.isNumericSpace();
System.assertEquals(false, b3);

isWhitespace() : This string method will return true, if the string contain only white spaces.

//Return true
String s1 = ' ';
Boolean b1 = s1.isWhitespace();
System.assertEquals(true, b1);

//Return true
String s2 = '';
Boolean b2 = s2.isWhitespace();
System.assertEquals(true, b2);

//Return false
String s3 = 'BISWA 1234';
Boolean b3 = s3.isWhitespace();
System.assertEquals(false, b3);

containsWhitespace() : This string method will return true, if the string contain white spaces.

//Return true
String s1 = 'Biswajeet Samal';
Boolean b1 = s1.containsWhitespace();
System.assertEquals(true, b1);

//Return true
String s2 = 'Biswajeet 1234';
Boolean b2 = s2.containsWhitespace();
System.assertEquals(true, b2);

//Return true
String s3 = 'BISWA ';
Boolean b3 = s3.containsWhitespace();
System.assertEquals(true, b3);

//Return false
String s4 = 'Biswajeet';
Boolean b4 = s4.containsWhitespace();
System.assertEquals(false, b4);

isAllLowerCase() : This string method will return true, if the string contain all characters in lowercase.

//Return true
String s1 = 'biswajeet';
Boolean b1 = s1.isAllLowerCase();
System.assertEquals(true, b1);

//Return false
String s2 = 'Biswajeet';
Boolean b2 = s2.isAllLowerCase();
System.assertEquals(false, b2);

isAllUpperCase() : This string method will return true, if the string contain all characters in uppercase.

//Return true
String s1 = 'BISWAJEET';
Boolean b1 = s1.isAllUpperCase();
System.assertEquals(true, b1);

//Return false
String s2 = 'Biswajeet';
Boolean b2 = s2.isAllUpperCase();
System.assertEquals(false, b2);

1 Star2 Stars3 Stars4 Stars5 Stars (14 votes, average: 5.00 out of 5)
Loading...