Author Archives: Biswajeet

About Biswajeet

Biswajeet is my Name, Success is my Aim and Challenge is my Game. Risk & Riding is my Passion and Hard Work is my Occupation. Love is my Friend, Perfection is my Habit and Smartness is my Style. Smiling is my Hobby, Politeness is my Policy and Confidence is my Power.

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);

Salesforce Lightning Aura Method

Use aura:method to define a method as part of a component’s API. This enables you to directly call a method in a component’s client-side controller instead of firing and handling a component event. Using aura:method simplifies the code needed for a parent component to call a method on a child component that it contains.

Child Component:

<!--Child.cmp-->
<aura:component >
    <aura:method name="messageMethod" action="{!c.getMessage}" access="public">
        <aura:attribute name="param1" type="String" default="Hello"/> 
        <aura:attribute name="param2" type="String" default="World"/> 
    </aura:method>
</aura:component>

Child Component JS Controller:

({
    getMessage : function(component, event) {
        //get method paramaters
        var params = event.getParam('arguments');
        if (params) {
            var param1 = params.param1;
            var param2 = params.param2;
            alert(param1 + " " + param2);
        }
    }
})

Parent Component:

<!--Parent.cmp-->
<aura:component>    
    <div class="slds-m-around_xx-large">
        <!-- Child Component -->
        <c:Child aura:id="childCmp"/>
        <!-- On button click child aura:method will be called-->
        <lightning:button variant="brand" label="Call Aura Method" onclick="{!c.callAuraMethod}" />
    </div>
</aura:component>

Parent Component JS Controller:

({
    callAuraMethod : function(component, event, helper) {
        //Call Child aura method
        var childComponent = component.find("childCmp");
        var message = childComponent.messageMethod();
    }
})

Output:

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" label="First Name" value="{!v.objLead.FirstName}" />
            </div>
            <div class="form-group">
                <lightning:input name="lname" label="Last Name" value="{!v.objLead.LastName}" />
            </div>
            <div class="form-group">
                <lightning:input name="emailId" label="Email" value="{!v.objLead.Email}" />
            </div>
            <div class="form-group">
                <lightning:input name="company" 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:

({
    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"){
                helper.resetForm(component, event);
                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);
    },
    
    handleCancel : function(component, event, helper){
        helper.resetForm(component, event);
    }
})

Lightning JS Helper:

({
    resetForm : function(component, event){
        var objLead = {'sobjectType': 'Lead',
                       'FirstName': '',
                       'LastName': '',
                       'Email': '', 
                       'Company': ''
                      };
        component.set("v.objLead",objLead);
    }
})

Output:

Wrapper Class In Lightning Component

Lightning Component:

<!--
Name: ContactList.cmp
--> 
<aura:component controller="ContactController">
    <!--Declare Event Handlers-->  
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
    
    <!--Declare Attributes-->
    <aura:attribute name="contactList" type="ContactController.ContactWrapper[]" />   
    <aura:attribute name="isSelectAll" type="boolean" default="false"/>
    
    <div class="slds-m-around_xx-large">
        <h1 class="slds-text-heading--medium">Contacts</h1>
        <br/>
        <!--Contact List Table-->
        <table class="slds-table slds-table--bordered slds-table--cell-buffer" role="grid">      
            <thead>  
                <tr class="slds-text-title--caps">
                    <th>           
                        <label class="slds-checkbox">
                            <ui:inputCheckbox value="{!v.isSelectAll}" change="{!c.handleSelectAllContacts}" aura:id="selectAll"/>
                            <span class="slds-checkbox--faux" />
                            <span class="slds-form-element__label"></span>
                        </label>
                    </th>
                    <th scope="col">
                        <div class="slds-truncate" title="Name">Name</div>
                    </th>
                    <th scope="col">
                        <div class="slds-truncate" title="Account">Account</div>
                    </th>
                    
                    <th scope="col">
                        <div class="slds-truncate" title="Phone">Phone</div>
                    </th>
                    
                    <th scope="col">
                        <div class="slds-truncate" title="Email">Email</div>
                    </th>
                </tr>
            </thead>
            <tbody>        
                <aura:iteration items="{!v.contactList}" var="con">
                    <tr>
                        <th>
                            <label class="slds-checkbox">
                                <ui:inputCheckbox aura:id="checkContact" value="{!con.isSelected}" text="{!con.Id}"/>
                                <span class="slds-checkbox--faux" />
                                <span class="slds-form-element__label"></span>
                            </label>
                        </th>
                        <th scope="row">
                            <div class="slds-truncate" title="{!con.Name}">{!con.Name}</div>
                        </th>
                        <td>
                            <div class="slds-truncate" title="{!con.Account}">{!con.Account}</div>
                        </td>
                        <th scope="row">
                            <div class="slds-truncate" title="{!con.Phone}">{!con.Phone}</div>
                        </th>
                        <td>
                            <div class="slds-truncate" title="{!con.Email}">{!con.Email}</div>
                        </td>
                    </tr>
                </aura:iteration>
            </tbody>
        </table>
        <div>
            <br/>
            <lightning:button label="Submit" class="slds-button_brand" onclick="{!c.handleSelectedContacts }"  />
        </div>
    </div>
</aura:component>

Lightning JS Controller:

({
    //get Contact List from apex controller
    doInit : function(component, event, helper) {
        var action = component.get("c.getContactList");
        action.setCallback(this, function(result){
            var state = result.getState();
            if (component.isValid() && state === "SUCCESS"){
                component.set("v.contactList",result.getReturnValue());   
            }
        });
        $A.enqueueAction(action);
    },
    
    //Select all contacts
    handleSelectAllContacts: function(component, event, helper) {
        var getID = component.get("v.contactList");
        var checkvalue = component.find("selectAll").get("v.value");        
        var checkContact = component.find("checkContact"); 
        if(checkvalue == true){
            for(var i=0; i<checkContact.length; i++){
                checkContact[i].set("v.value",true);
            }
        }
        else{ 
            for(var i=0; i<checkContact.length; i++){
                checkContact[i].set("v.value",false);
            }
        }
    },
    
    //Process the selected contacts
    handleSelectedContacts: function(component, event, helper) {
        var contactList = component.get("v.contactList");
        var isSelectAll = component.get("v.isSelectAll");
        
        var selectedContacts = [];
        
        if(isSelectAll){
            selectedContacts = contactList;
        }
        else{
            var k = 0;
            for (var i=0; i<contactList.length; i++){
                var c = contactList[i];
                if(c.isSelected) {
                    selectedContacts[k] = c;
                    k++; 
                }     
            }
        }
        
        if(selectedContacts.length > 0){
            var contactRecords = JSON.stringify(selectedContacts);
            var action = component.get("c.processSelectedContacts");
            action.setParams({
                contactRecords : contactRecords
            });
            action.setCallback(this, function(result){
                var state = result.getState();
                if (component.isValid() && state === "SUCCESS"){
                    alert('Success in calling server side action');
                }
                else if(state == "ERROR"){
                    alert('Error in calling server side action');
                }
            });
            $A.enqueueAction(action);
        }
    }
})

Apex Controller:

public class ContactController {
    
    @AuraEnabled
    Public static List<ContactWrapper> getContactList(){
        List<ContactWrapper> contactList = new List<ContactWrapper>(); 
        //get all contact list
        List<Contact> conList = [SELECT Id, Name, Account.Name, Phone, Email FROM Contact LIMIT 10];
        for(Contact con : conList){
            ContactWrapper obj = new ContactWrapper();
            obj.ContactId = con.Id;
            obj.Name = con.Name;
            obj.Account = con.Account.Name;
            obj.Phone = con.Phone;
            obj.Email = con.Email;
            obj.isSelected = false; 
            contactList.add(obj);
        }
        return contactList;
    }
    
    @AuraEnabled
    Public static void processSelectedContacts(string contactRecords){
        system.debug('contactRecords-' + contactRecords);
        List<ContactWrapper> contactList = new  List<ContactWrapper>();
        if(!string.isBlank(contactRecords)){
            contactList = (List<ContactWrapper>)System.JSON.deserialize(contactRecords,List<ContactWrapper>.class);
            system.debug('contactList-' + contactList);
        }
    }
    
    public class ContactWrapper{
        @AuraEnabled
        public String ContactId {get;set;}
        @AuraEnabled
        public String Name {get;set;}
        @AuraEnabled
        public String Account {get;set;}
        @AuraEnabled
        public String Phone {get;set;}
        @AuraEnabled
        public String Email {get;set;}
        @AuraEnabled
        public boolean isSelected {get;set;}
    }
}

Dynamically Creating Lightning Components

Sample Component:

<!--
Name: Sample.cmp
--> 
<aura:component >    
    <div class="slds-m-around_xx-large">
        <label class="mdp-form-user-element__label" id="enteredName"></label><br/><br/>
        <lightning:button label="Add Your Name" variant="brand" onclick="{!c.handlePopup}"/>
    </div>
    {!v.body }
</aura:component>

Sample Component JS Controller:

({
    handlePopup : function(component, event,helper) {
        //Create Dynamic Component
        $A.createComponent('c:SampleModalPopup', {
            title: 'Please enter your name',
            
        }, function attachModal(modalCmp, status) {
            if (component.isValid() && status === 'SUCCESS') {
                var body = component.get("v.body");
                body.push(modalCmp);
                component.set("v.body", body);    
            }
        });
    }
})

ModalPopup Component:

<!--
    Name: ModalPopup.cmp
--> 
<aura:component >
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:attribute name="title" type="String" />
    <div aura:id="modalDiv">
        <div role="dialog" class="slds-modal slds-fade-in-open">
            <div class="slds-modal__container">
                <div class="slds-modal__header">
                    <button class="slds-button slds-modal__close slds-button--icon-inverse" title="Close" onclick="{!c.handleCloseModal}">
                        X<span class="slds-assistive-text">Close</span>
                    </button>
                    <h1 class="slds-text-heading--medium">{!v.title}</h1>
                </div>
                
                <!--Modal Box Header-->
                <div class="slds-modal__content slds-p-around--medium">
                    <input type="text" placeholder="Please enter your name" id="userName" autofocus="autofocus" class="slds-input"/>
                </div>
                <!--Modal Box Button-->
                <div class="slds-modal__footer">
                    <lightning:button label="Submit" class="slds-button_brand" onclick="{!c.handleSubmit}"  />
                    <lightning:button label="Cancel" class="slds-button" onclick="{!c.handleCloseModal }"  />
                </div>
            </div>
        </div>
        <div class="slds-backdrop slds-backdrop--open"></div>            
    </div>
</aura:component>

ModalPopup JS Controller:

({
    doInit : function(component, event, helper) {
        console.log('Modal Popup Load');
    },
    
    handleSubmit : function(component, event, helper){
        var userName = document.getElementById("userName");
        var enteredName = document.getElementById("enteredName");
        enteredName.innerHTML = userName.value;
        
        var popupWindow = component.find('modalDiv').getElement();
        if(popupWindow){
            popupWindow.style.display = 'none';
        }
    },
    handleCloseModal : function(component, event, helper){
        var popupWindow = component.find('modalDiv').getElement();
        if(popupWindow){
            popupWindow.style.display = 'none';
        }
    }
})

Output: