Tag Archives: Apex

Apex Controller Exception Handling in Lightning Component

When we use an Apex Controller method in lightning JS Controller or Helper, sometimes error occurs on execution of apex method. 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 apex exception and how to show custom messages in Lightning Component.

In below example I’ve used Lead object FirstName, LastName, Email & Company Field. In lead object LastName & Company fields are required. If we will submit the form without the required fields, then the apex method will throw the error message, which we can show in lightning component or we can add our custom message there.

Apex Controller:

public class SampleAuraController {
    
    @AuraEnabled
    Public static void createLead(Lead objLead){
        try{
            //Insert Lead Record
            insert objLead; 
        }catch(DmlException e) {
            //get DML exception message
            throw new AuraHandledException(e.getMessage());
        }catch(Exception e){
            //get 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="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" label="First Name" value="{!v.objLead.FirstName}" />
            </div>
            <div class="form-group">
                <lightning:input name="lname" type="text" maxlength="50" label="Last Name" value="{!v.objLead.LastName}" />
            </div>
            <div class="form-group">
                <lightning:input name="emailId" type="email" maxlength="100" label="Email" value="{!v.objLead.Email}" />
            </div>
            <div class="form-group">
                <lightning:input name="company" type="text" maxlength="50" label="Company" value="{!v.objLead.Company}" />
            </div>
        </div>
        <br/>
        <lightning:button variant="brand" label="Submit" onclick="{!c.handleLeadSave}" />              
    </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:

LastName Required Field Error Message:

Access Apex Class Properties in Lightning Component

Apex Class:

public class SampleAuraController {
    
    //Properties
    @AuraEnabled public String FirstName {get;set;}
    @AuraEnabled public String LastName {get;set;}
    
    @AuraEnabled
    public static SampleAuraController getData() {
        SampleAuraController obj = new SampleAuraController();
        obj.FirstName = 'Biswajeet';
        obj.LastName = 'Samal';
        return obj;
    }
}

Lightning Component:

<!--Sample.cmp--> 
<aura:component controller="SampleAuraController" implements="flexipage:availableForAllPageTypes,force:appHostable">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:attribute name="obj" type="SampleAuraController"/>
    <!--Component Start-->
    <div class="slds-m-around_xx-large">
        <strong>First Name : {!v.obj.FirstName}</strong>
        <br/>
        <strong>Last Name : {!v.obj.LastName}</strong>
    </div>
    <!--Component End-->
</aura:component>

Lightning Component JS Controller:

({
    doInit : function(component, event, helper) {
        var action = component.get('c.getData');
        action.setCallback(this,function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                var result = response.getReturnValue();
                component.set('v.obj', result);
            }
        });
        $A.enqueueAction(action);
    }
})

Output:

Salesforce Test Class Data For ContentDocument

Sample Code:

//Create Document
ContentVersion cv = new ContentVersion();
cv.Title = 'Test Document';
cv.PathOnClient = 'TestDocument.pdf';
cv.VersionData = Blob.valueOf('Test Content');
cv.IsMajorVersion = true;
Insert cv;

//Get Content Version
List<ContentVersion> cvList = [SELECT Id, Title, ContentDocumentId FROM ContentVersion WHERE Id = :cv.Id];
System.assertEquals(cvList.size(), 1);

//Get Content Documents
List<ContentDocument> cdList = [SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument];
System.assertEquals(cdList.size(), 1);

Salesforce Test Class Data For ContentDocumentLink

Sample Code:

//Create Document Parent Record
Account acc = new Account(Name='Test Account');
Insert acc;

//Create Document
ContentVersion cv = new ContentVersion();
cv.Title = 'Test Document';
cv.PathOnClient = 'TestDocument.pdf';
cv.VersionData = Blob.valueOf('Test Content');
cv.IsMajorVersion = true;
Insert cv;

//Get Content Documents
Id conDocId = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =:cv.Id].ContentDocumentId;

//Create ContentDocumentLink 
ContentDocumentLink cdl = New ContentDocumentLink();
cdl.LinkedEntityId = acc.Id;
cdl.ContentDocumentId = conDocId;
cdl.shareType = 'V';
Insert cdl;

Get Data From Visualforce Controller Extension Without SOQL Query

When a Visualforce page is loaded, the fields accessible to the page are based on the fields referenced in the Visualforce markup. But we can use StandardController.addFields(List fieldNames) method, which adds a reference to each field specified in fieldNames so that the controller can explicitly access those fields as well.

public with sharing class AccountControllerExt {
    public Account acc {get; set;}
    
    public AccountControllerExt(ApexPages.StandardController controller) {
        List<String> accFieldList = new List<String>();
        //Passing a list of field names to the standard controller
        controller.addFields(new List<String>{'Id', 'Name', 'AccountNumber', 'Website', 'Phone','Type', 'Industry'});
        //Standard controller to retrieve the field data of the record
        acc = (Account)controller.getRecord();
    }
}