Tag Archives: Apex

Padding String in Salesforce Apex

Left Pad:

leftPad(length): Returns the current String padded with spaces on the left and of the specified length. If length is less than or equal to the current String size, the entire String is returned without space padding.

String name = 'biswa';
String lpName = name.leftPad(8);
System.debug('LeftPad-' + lpName);
System.assertEquals('   biswa', lpName);

leftPad(length, padStr): Returns the current String padded with String padStr on the left and of the specified length. padStr to pad with; if null or empty treated as single blank.

Integer num = 555;
String lpString = String.valueOf(num).leftPad(5, '0');
System.debug('LeftPad-' + lpString);
System.assertEquals('00555', lpString);

Right Pad:

rightPad(length): Returns the current String padded with spaces on the right and of the specified length. If length is less than or equal to the current String size, the entire String is returned without space padding.

String name = 'biswa';
String rpName = name.rightPad(8);
System.debug('RightPad-' + rpName);
System.assertEquals('biswa   ', rpName);

rightPad(length, padStr): Returns the current String padded with String padStr on the right and of the specified length. padStr to pad with; if null or empty treated as single blank.

Integer num = 555;
String rpString = String.valueOf(num).rightPad(5, '0');
System.debug('RightPad-' + rpString);
System.assertEquals('55500', rpString);

jQuery Data Tables in Visualforce Page

Here is an example of ‎jQuery Data tables using in Visualforce. It will give you the pagination and search functionality in Visualforce page. Here I’m displaying list of account records.

Apex Class:

public class SampleController{
    public List<Account> accList {get; set;}
    
    public SampleController(){
    accList = [SELECT Name, AccountNumber, Phone FROM Account LIMIT 10000];
    }

}

Visualforce Page:

<apex:page Controller="SampleController" readOnly="true" tabStyle="Account" sidebar="false">
    <head>
        <apex:includescript value="//code.jquery.com/jquery-1.11.1.min.js"/>
        <apex:includescript value="//cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js"/>
        <apex:stylesheet value="//cdn.datatables.net/1.10.4/css/jquery.dataTables.css"/>
        <script>
        j$ = jQuery.noConflict();
        j$(document).ready( function () {
            var accTable = j$('[id$="accTable"]').DataTable({
                
            });
        });
        </script>
    </head>
    <body>
        <table id="accTable" class="display">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Account Number</th>
                    <th>Phone</th>
                </tr>
            </thead>
            <tbody>
                <apex:repeat value="{!accList}" var="acc">
                    <tr>
                        <td>{!acc.Name}</td>
                        <td>{!acc.AccountNumber}</td>
                        <td>{!acc.Phone}</td>
                    </tr>
                </apex:repeat>
            </tbody>
        </table>
    </body>
</apex:page>

Output:

Iterate Map values in Lightning Component

Apex Controller:
Create below apex controller to get the Map value.

public class MapAuraController {
    
    @AuraEnabled
    public static map<Integer, String> getMap(){
        Map<Integer, String> companyMap = new Map<Integer, String>();
        //Put value in Map 
        companyMap.put(1,'Salesforce');
        companyMap.put(2,'SAP');  
        companyMap.put(3,'Oracle');  
        companyMap.put(4,'Microsoft');  
        //return map  
        return companyMap;
    }
}

Child Component:
Create below Child.cmp for display the Map key values on component.

<!--Child.cmp-->
<aura:component >
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:attribute name="map" type="map"/>
    <aura:attribute name="key" type="string"/>
    <aura:attribute name="value" type="string"/>
    <p>{!v.key} - {!v.value}</p>
</aura:component>

Child Component JS Controller:
Create below JavaScript Controller for above Child.cmp component.

({
    doInit : function(component, event, helper) {
        var key = component.get("v.key");
        var map = component.get("v.map");
        component.set("v.value" , map[key]);
    },
})

Parent Component:
Create below Parent.cmp, this is the main component. By this component we retrieve the map value from apex controller and pass key and map attribute to Child.cmp component.

<!--Parent.cmp-->
<aura:component controller="MapAuraController">
    <!--declare attributes-->
    <aura:attribute name="keyList" type="List"/>
    <aura:attribute name="companyMap" type="map"/>
    
    <ui:button label="Iterate Map" press="{!c.getMapCompany}"/>
    
    <!--Iterate the mapCompany-->
    <aura:iteration items="{!v.keyList}" var="key" >
        <c:Child map="{!v.companyMap}" key="{!key}"/>
    </aura:iteration>
</aura:component>

Parent Component:
Create below JavaScript Controller for above Parent.cmp component.

({
    getMapCompany: function(component, event, helper) {
        //call apex class method 
        var action = component.get('c.getMap');
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                //Create an empty array to store the map keys 
                var arrayMapKeys = [];
                //Store the response of apex controller (return map)     
                var result = response.getReturnValue();
                //Set the store response[map] to component attribute, which name is map and type is map.   
                component.set('v.companyMap', result);
                
                for (var key in result) {
                    arrayMapKeys.push(key);
                }
                //Set the list of keys.     
                component.set('v.keyList', arrayMapKeys);
            }
        });
        // enqueue the Action   
        $A.enqueueAction(action);
    }
})

Lightning Test App:

<!--Test.app-->
<aura:application extends="force:slds">
    <c:Parent />
</aura:application>

Output:

Avoid Recursive Trigger Calls In Salesforce

Recursion occurs when same code is executed again and again. It can lead to infinite loop and which can result to governor limit sometime. Sometime it can also result in unexpected output or the error “maximum trigger depth exceeded”. So, we should write code in such a way that it does not result to recursion.

For example, I’ve a trigger on Account object, which will be execute on before Update and after Update. In after Update I’ve some custom logic to update Account records. So, when I’m updating the Account records in After Update, it is throwing error “maximum trigger depth exceeded”. So, it is a recursion in apex trigger.

To avoid the situation of recursive call, we have to write code in such a way that the trigger will execute one time. To do so, we can create a class with a static Boolean variable with default value true. In the trigger, before executing the code keep a check that the variable is true or not.

Here in below trigger, I want to execute both before and after Update trigger only one time. I’m checking the static Boolean variable is true in both before and after Update trigger. In after update trigger changed the variable to false and after updating the account records, again changed the variable to true. In this way you can handle bulk of records in recursive trigger.

Apex Class:

public Class AccountTriggerHelper{
    //Trigger execution check variable
    public static Boolean runOnce = true;
    
    //On before update
    public void onBeforeUpdate(map<Id, Account> mapNewAccount, map<Id, Account> mapOldAccount){
        //Write your logic here
        System.debug('Is Before Update');
    }
    
    //On after update
    public void onAfterUpdate(map<Id, Account> mapNewAccount, map<Id, Account> mapOldAccount){
        Update [SELECT Id, Name FROM Account WHERE Id IN: mapNewAccount.keyset()];
        AccountTriggerHelper.runOnce = true;
        System.debug('Is After Update');
    }
}

Apex Trigger:

trigger AccountTrigger on Account(before Update, after Update) {
    
    AccountTriggerHelper helper = new AccountTriggerHelper();
    
    if(Trigger.isBefore && Trigger.isUpdate && AccountTriggerHelper.runOnce){
        helper.onBeforeUpdate(Trigger.newMap, Trigger.OldMap);     
    }
    
    if(Trigger.isAfter && Trigger.isUpdate && AccountTriggerHelper.runOnce){
        AccountTriggerHelper.runOnce = false;
        helper.onAfterUpdate(Trigger.newMap, Trigger.OldMap);
    }
}

Debug Log:

Check Case Owner is a User or Queue

Check Case Owner in Apex Class.

//Check object Id in Apex 
if(string.valueOf(c.OwnerId).startsWith('005')){
    //Owner is User       
}

if(string.valueOf(c.OwnerId).startsWith('00G')){
    //Owner is Queue
}

Check Case Owner in Apex Trigger.

//In Apex Trigger
for (Case objCase : Trigger.new) { 
    If (objCase.OwnerID.getsobjecttype() == User.sobjecttype) {
        /*Code if Owner is User*/
    }
    else{
        /*Code if Owner is Queue*/ 
    }
}

Check Case Owner by SOQL query.

//By Query Owner.Type Field
List<Case> caseList = [SELECT Id, CaseNumber, OwnerId, Owner.Name, Owner.Type FROM Case];

for (Case objCase : caseList){
    If (objCase.Owner.Type == User.sobjecttype) {
        /*Code if Owner is User*/
    }
    else{
        /*Code if Owner is Queue*/ 
    }
}

Check Case Owner in Process Builder.

//Check in Process Builder
BEGINS([Case].OwnerId, "005") //Check Owner is User
BEGINS([Case].OwnerId, "00G") //Check Owner is Queue