Search This Blog

Monday, December 21, 2020

convert date to datetime in apex salesforce - Salesforce Globe For You

 convert date to datetime in apex salesforce  - Salesforce Globe For You 

Example:

Date dtTodayDate = System.Today();

Datetime dtTodayDateTime = datetime.newInstance(dtTodayDate.year(), dtTodayDate.month(),dtTodayDate.day());

system.debug('Date in DateTime:'+dtTodayDateTime);

Output:



Display date in MM/DD/YYYY format in apex salesforce - Salesforce Globe For You

 Display date in MM/DD/YYYY format in apex salesforce  - Salesforce Globe For You 

Solution: First convert date to dateTime field and then use format() to display in the required format.

Example:

Date dtTodayDate = System.Today();

Datetime dtTodayDateTime = datetime.newInstance(dtTodayDate.year(), dtTodayDate.month(),dtTodayDate.day());

string strDate = dtTodayDateTime.format('MM/dd/yyyy');

system.debug('Date in MM/DD/YYYY format:'+strDate);

Output:



Monday, December 14, 2020

How to display/show an error message at the respective field through trigger salesforce? - Salesforce Globe For You

 How to display/show an error message at the respective field through trigger salesforce?  - Salesforce Globe For You 

Problem: Assume while inserting Lead record,in case if Email field of Lead is empty ,need to display an error Message 'Please Enter Email' below the Email field itself.

Solution: use addError() method at it's respective record field to display Error message like this objLead.Email.addError('Please Enter Email'); where Email is field where error message to be displayed.

Example:

trigger ErrorMessageAtFieldLevel on Lead (before insert) {

    for(Lead objLead :trigger.new) {

        if(String.isBlank(objLead.Email)) {

            objLead.Email.addError('Please Enter Email');

        }

    }

}

Output: when you try creating a new Lead record without entering Email,it will through an error message at the Email field as shown below.



Wednesday, December 9, 2020

Dynamic multiple tabs in lwc Salesforce - Salesforce Globe For You

 Dynamic multiple tabs in lwc Salesforce  - Salesforce Globe For You 

LWC Component: dynamicTabsInLWC

dynamicTabsInLWC.html

<template>

    <lightning-tabset>

        <template for:each={lstTabs} for:item="tab">

            <lightning-tab label={tab.Name} key={tab.Name}>

                {tab.Id}

            </lightning-tab>

        </template>

    </lightning-tabset>

</template>

dynamicTabsInLWC.js

import { LightningElement,track } from 'lwc';

export default class DynamicTabsInLWC extends LightningElement {

    @track lstTabs = [

        {

            Id: 1,

            Name: 'Tab 1'

        },

        {

            Id: 2,

            Name: 'Tab 2'

        },

        {

            Id: 3,

            Name: 'Tab 3'

        },

    ];

    

}

dynamicTabsInLWC.js-meta.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__RecordPage</target>

        <target>lightning__AppPage</target>

        <target>lightning__HomePage</target>

    </targets>

</LightningComponentBundle>

Note:dynamically populate lstTabs variaable as per your requirement.

Output:



Friday, November 27, 2020

How to create a map of Group and GroupMembers apex salesforce - Salesforce Globe For You

 How to create a map of Group and GroupMembers apex salesforce  - Salesforce Globe For You 

Run the following piece of code in anonymous window.

Map<Group,List<GroupMember>> mapGroupGroupMembers = new Map<Group,List<GroupMember>>();

for(Group objGroup : [Select id,name,(select id,UserOrGroupId from GroupMembers) from Group]) {

    List<GroupMember> lstGroupMembers = new List<GroupMember>();

    if(!objGroup.GroupMembers.isEmpty()) {

        for(GroupMember objMember : objGroup.GroupMembers) {

        lstGroupMembers.add(objMember);    

        }

        mapGroupGroupMembers.put(objGroup,lstGroupMembers);

    } else {

        mapGroupGroupMembers.put(objGroup,lstGroupMembers);

    }

}

system.debug('mapGroupGroupMembers:'+mapGroupGroupMembers);

Output:



Thursday, November 26, 2020

is current year a leap year? apex salesforce - Salesforce Globe For You

 is current year a leap year? apex salesforce  - Salesforce Globe For You 

Solution: use isLeapYear() of Date to know if the given year is leap year or not.

Example: To check current year is leap year or not.

Run the piece of code below in anonymous window.

String year = system.today().year();

system.debug('Is current Year leap year:'+Date.isLeapYear(year));

output:



Tuesday, November 17, 2020

get all the child objects of a parent object salesforce - Salesforce Globe For You

 get all the child objects of a parent object salesforce  - Salesforce Globe For You 

In this example,all the child objects of opportunity object are fetched.

Apex Class:OpportunityChildObjectController

public class OpportunityChildObjectController {

    public list<String> lstOppChildObjects {get;set;}

    public void getChildObjectsOfOpp() {

        lstOppChildObjects = new List<String>();

        Schema.DescribeSObjectResult objSchemaResult = Opportunity.SObjectType.getDescribe();

        for (Schema.ChildRelationship objChildRelationship : objSchemaResult.getChildRelationships()) {

            lstOppChildObjects.add(string.valueOf(objChildRelationship.getChildSObject()));

        }

        system.debug('Opportunity Related Child Objects are:'+lstOppChildObjects);

    }

}

Visualforce Page:OpportunityChildObjects

<apex:page controller="OpportunityChildObjectController" action="{!getChildObjectsOfOpp}">

    <b>Opportunity Child Objects are:</b><br/>

    <apex:variable var="index" value="{!1}" />

    <apex:repeat value="{!lstOppChildObjects}" var="objName" id="OppRelatedChildObjects">

        {!index}) <apex:outputText value="{!objName}" id="theValue"/><br/>

        <apex:variable var="index" value="{!index + 1}" />

    </apex:repeat>

</apex:page>

Output:



SOQL to get the public groupId based on the group name salesforce - Salesforce Globe For You

 SOQL to get the public groupId based on the group name salesforce  - Salesforce Globe For You 

Solution:use the following query

select id,name,type from group where group.Name ='Test Public Group'

where Name is the name of the group.

Note: Use the label of the group for the group name.

Output:


Tuesday, November 3, 2020

Aggregate Query to get the minimum date of all the child records associated with a parent record in salesforce - Salesforce Globe For You

 Aggregate Query to get the minimum date of all the child records(opportunities) associated with a parent record(Account) in salesforce  - Salesforce Globe For You 

Requirement: I need to get the minimum clode date of all the opportunities associated to a Account Record.

Solution:

List<AggregateResult> lstAggregateResult = new List<AggregateResult>();

lstAggregateResult = [Select accountId,Min(closeDate) minDate from opportunity where accountId != null group by accountId];

for(AggregateResult objResult:lstAggregateResult) {

    system.debug('Account Id: '+objResult.get('accountId')+' and its associated opportunity min date is:'+objResult.get('minDate'));

}

Output:



Monday, October 12, 2020

what is connected app in salesforce? - Salesforce Globe For You

 what is connected app in salesforce  - Salesforce Globe For You 

Connected App:A connected app is a framework that helps external application to integrate with salesforce using API's and standard protocols like SAML,OAuth and OpenID connect.

These protocols are used by connected App to authenticate,authorize and provide single sign-on (SSO) for external apps.

The connected app captures metadata about the external app such as which protocol the external app uses and where it runs etc and then provides the same information to salesforce.Salesforce then grants access to external application to access it's data by attaching some policies that define access restrictions.

Uses of connected App:

1)Access Data with API integration: if web based or mobile applications wants to pull data from salesforce,you can use connected app as client to request the data.

2)Integrate service providers with salesforce.

3)provide authorization for extrnal API gateways

4)Manage access to third party apps.

Go through the following trialhead for more details

https://trailhead.salesforce.com/content/learn/modules/connected-app-basics

Thursday, October 8, 2020

difference between Managed and Unmanaged package in salesforce - Salesforce Globe For You

 Packages: Whenever you need to use the app exchange products or whenever you need to deploy components from one org to another,you can use packages.

Package is a collection of related components like apps,tabs,apex classes,visualforce pages etc.

Whenever you need to use app exchange product,the product related components are packaged in a package which you can directly install and use.

you can create a package in one org and can use the package url to install it in other org.

Packages come in 2 flavours.Managed and Unmanaged.

Differences:

you cannot customize(change) the  code or metadata if required in Managed package but you can do that in unManaged package.

If you use Managed package,upgrades happen automatically when new version released but if you use unManaged package,upgrades won't happen automatically.

In Managed package,the components of the package don’t count against the org limits(tab limits,object limits,app limits etc). where as in unManaged,limits count.

What is AppExchange in Salesforce - Salesforce Globe For You

 What is AppExchange in Salesforce  - Salesforce Globe For You 

AppExhange: AppExchange ia a secure,trusted marketplace(including free and paid) for all salesforce related apps,lightnning components and many more.

Its a collection of prebuilt apps which you easily install and use which provides solutions for most of your usecases or requirements.

For example if you need to integrate with some external system or if you need to build some complex functionalities and you don't have enough time to build it from scratch,then you can go to AppExchange(https://appexchange.salesforce.com/) and search to find if there are any existing apps which can be used for your usecase.If you find necessary app,then you can directly install and use it.



Note: AppExchange products may be of free or paid.

AppExchange also  listed the consultants who have experience in building the apps that you need.You can take help of that consultant to build custom app to fulfil your requirement.

To learn more about the AppExchange,go through the following AppExchange trailhead salesforce provided.

https://trailhead.salesforce.com/content/learn/modules/appexchange_basics?trail_id=force_com_admin_intermediate


Tuesday, October 6, 2020

How to reduce or change size of lightning:icon in aura component? - Salesforce Globe For You

 How to reduce or change size of lightning:icon in aura component?  - Salesforce Globe For You 

solution:use the size attribute of lightning:icon to change it's size.

size="xx-small"   very very small icon

size="medium"     medium size icon.

Example:LightningIconSize.cmp

<aura:component >

    <div class="slds-align_center" style="padding-left:100px">

        very very small Icon: <lightning:icon iconName="action:delete" size="xx-small" alternativeText="Delete" title="Delete" /><br/><br/>

        very small Icon: <lightning:icon iconName="action:delete" size="x-small" alternativeText="Delete" title="Delete"/><br/><br/>

        small Icon: <lightning:icon iconName="action:delete" size="small" alternativeText="Delete" title="Delete" /><br/><br/>

        medium Icon: <lightning:icon iconName="action:delete" size="medium" alternativeText="Delete" title="Delete" /><br/><br/>

        large Icon: <lightning:icon iconName="action:delete" size="large" alternativeText="Delete" title="Delete" />

    </div>

</aura:component>

TestApp.app

<aura:application extends="force:slds">

<c:LightningIconSize/>

</aura:application>

Output:



how to display toggle icon or toggle button in aura component - Salesforce Globe For You

 how to display toggle icon or toggle button in aura component  - Salesforce Globe For You 

Example:ToggleIcon.cmp

<aura:component >

    <aura:attribute name="checkboxValue" type="boolean" default="false"/> 

<lightning:input type="toggle" label="Toggle Button:" aura:id="toggleButton" checked="false" name="toggleButton"  onchange="{!c.changeCheckboxValue}"/><br/>

The toggle value is:<b>{!v.checkboxValue}</b>

</aura:component>

ToggleIconController.js

({

changeCheckboxValue : function(component, event, helper) {

        // get the toggleButton element and check its value

var togglebuttonValue = component.find("toggleButton").get("v.checked");

        component.set("v.checkboxValue",togglebuttonValue);

}

})

TestApp.app

<aura:application extends="force:slds">

<c:ToggleIcon/>

</aura:application>

Output:



Shortcut to take screenshot in Macbook Pro

 Shortcut to take screenshot in Macbook Pro

Solution:Use command+Shift+4 and then select the area that you want to take screenshot.

use command+shift+3 to take screenshot of entire page.

Monday, September 28, 2020

How to check whether a salesforce instance is sandbox or not in apex Salesforce - Salesforce Globe For You

 How to check whether a salesforce instance is sandbox or not in apex Salesforce  - Salesforce Globe For You 

Solution: The 'IsSandbox' field of the organization object in salesforce gives the information where the instance is sandbox or production.

Name field:Name of the organization

InstanceName field:gives the instance name.

URLhttps://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_organization.htm

Go to query editor of developer console and use the following query as shown in image

Select id, IsSandbox, OrganizationType from organization

Output:



How to know which salesforce Edition the salesforce instance is - Salesforce Globe For You

 How to know which salesforce Edition the salesforce instance is  - Salesforce Globe For You 

Solution: The 'OrganizationType' field of the organization object gives the edition of the salesforce.

URL: https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_organization.htm

Go to query editor of developer console and use the following query as shown in image

Select id, IsSandbox, OrganizationType from organization

Output:




How to get all the values of a picklist field salesforce - Salesforce Globe For You

 How to get all the values of a picklist field salesforce  - Salesforce Globe For You 

Here in this example getting the leadSource (picklist) field values of Lead object.

Apex class:

public class PicklistValuesController {

    public List<String> lstLeadStatus {get;set;}

    public PageReference getLeadStatusValues() {

        lstLeadStatus = new List<String>();

        Schema.DescribeFieldResult fieldResult = Lead.LeadSource.getDescribe();

        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();

        for (Schema.PicklistEntry a : ple ) {

          lstLeadStatus.add(a.getValue());

        }

        system.debug('List Of Values:'+lstLeadStatus);

        return null;

    }

}

Visualforce Page:LeadStatusValues

<apex:page controller="PicklistValuesController" action="{!getLeadStatusValues}">

<b>The Lead Status Values are:</b><br/>

<apex:repeat value="{!lstLeadStatus}" var="staus">

   {!staus}<br/>

</apex:repeat>

</apex:page>

Output:



Friday, September 25, 2020

Dynamic soql to query records with a variable to define limit in apex salesforce - Salesforce Globe For You

 Dynamic soql to query records with a variable to define limit in apex salesforce  - Salesforce Globe For You 

Solution:Assume iLimit is a variable to set limit.

The query will be like this

[Select id,name from Lead limit :iLimit]; 

Note: keep space after limit and add ':'

Example:

Apex class:LimitVariableController

public class LimitVariableController {

    public static void getLeads(integer iLimit) {

        List<Lead> lstLead = new List<Lead>();

        lstLead = [Select id,name from Lead limit :iLimit];

        system.debug('Leads List:'+lstLead);

    }

}

When we run the following line from anonymous window of developer console,

LimitVariableController.getLeads(2);

the output will be like this.





How to display specific number of elements from a list in aura component - Salesforce Globe For You

 How to display specific number of elements from a list in aura component  - Salesforce Globe For You 

Problem: Need to display specified number of elements from a list instead of displaying all elements.

Solution: There is one attribute 'end' in <aura:iteration> tag which can be used for this purpose.The End attribute species the index(excluding) till which the list should iterate.

The end specifies the number of elements to display:If end is 2,it displays 2 elements and if end is 5 ,it displays 5 elements from the list.

Example:

ListIterator.cmp

<aura:component>

<aura:iteration items="1,2,3,4,5,6,7,8,9" var="num" end="4">

        {!num}<br/>

    </aura:iteration>

</aura:component>

TestApp.app

<aura:application extends="force:slds">

<c:ListIterator/>

</aura:application>

Output:



when end is change to 6,output is



How to get headers information in rest resource class Salesforce - Salesforce Globe For You

 How to get headers information in rest resource class Salesforce  - Salesforce Globe For You 

Solution: There is a property called 'Headers' in RestResource class which returns the headers that are received by the request.

Example:Assume we are passing the header 'Header1' with value '123' in the request.

Apex class:

@restResource(urlMapping='/getAccountInfo/*')

global class HeaderInfoInRestResource {

    @HttpGet

    global static Account getAccount() {

        RestRequest req = RestContext.request;

        RestResponse res = RestContext.response;

        Map<String,String> mapHeader = new Map<String,String>();

        mapHeader = req.Headers;

        system.debug('mapHeader'+mapHeader);

        String header1Value ='';

        if(mapHeader.containsKey('Header1')) {

            header1Value = mapHeader.get('Header1');

            system.debug('header1Value'+header1Value);

        }

        return [Select id,name from Account limit 1];

    }

}

Open workbench https://workbench.developerforce.com/login.php and sign in with your salesforce instance credentials.

Go to Utilities tab and click on 'Rest Explorer'.

Use Get Request,add the header header1 as shown in the image and then execute.

Output:



Thursday, September 24, 2020

Salesforce release cycle information(spring,summer and winter readiness and release dates) - Salesforce Globe For You

 Salesforce release cycle information(spring,summer and winter readiness and release dates)  - Salesforce Globe For You 

Salesforce  delivers multiple innovative features 3 times a year during their seasonal releases: Spring, Summer, and Winter.

In general, Spring Feb-May,Summer June-Sep and Winter October-Jan.

To know the important dates about each release information,go to 

https://status.salesforce.com/products/Salesforce_Services

and then select the region and instance as shown in the image below.



Go to the maintaince tab.



In this tab you will find the information about each release.

Its always better to go through this https://status.salesforce.com/products/Salesforce_Services url atleast once in every 2 months to know the releases information better.

Wednesday, September 9, 2020

How to upload files from aura component salesforce Lightning - Salesforce Globe For You

 How to upload files from aura component salesforce Lightning  - Salesforce Globe For You 

Solution:Use <lightning:fileUpload> component in aura component to upload files.

To associate the uploaded file to salesforce record,assign the recordId of that record to the 'recordId' attribute of <lightning:fileUpload> component.

Example:

fileUpload.cmp

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,

forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global"><aura:attribute name="recordId" type="String" />

 <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

<div class="slds-page-header">

 <div class="slds-align_absolute-center slds-text-title_bold" style="height:5rem">File Upload</div>

 <lightning:fileUpload label="Attach File" name="fileUploader" multiple="true"  recordId="{!v.recordId}" onuploadfinished="{!c.handleUploadFinished}" />

 </div>

</aura:component>

fileUploadController.js

({

doInit : function(component, event, helper) {

 },

handleUploadFinished : function(component, event, helper) {

var recordId = component.get('v.recordId');

var str = "Files uploaded to Notes and Attachment under this record"+recordId;

alert(str);

 }

})

You can drag and drop this component to any record detail page to test.

In this example I dragged this component to Lead record page and uploaded the file.

Output:





Sunday, September 6, 2020

How to lock a salesforce record or records in Apex? - Salesforce Globe For You

How to lock a salesforce record or records in Apex?  - Salesforce Globe For You 

Solution: Use 'FOR Update' keyword after the SOQL query to lock the records.

Example:If you want to lock the records returned by the following query

List<Lead> lstLead = new List<Lead>();

lstLead = [Select id,name from Lead];

then modify the query as shown below

List<Lead> lstLead = new List<Lead>();

lstLead = [Select id,name from Lead For UPDATE];

When records are locked,no other user is allowed to update this records until the lock gets released.The lock automatically gets released after transaction completes.

Note:You cannot use 'Order By' when you are using 'FOR UPDATE' in SOQL query.

How to get size of a map in Apex Salesforce - Salesforce Globe For You

 How to get size of a map in Apex Salesforce  - Salesforce Globe For You 

Solution:Use size() to get size of map.

Example:

Map<String,String> alphabetMap = new Map<string,String>();

alphabetMap.put('A','Apple');

alphabetMap.put('B','Ball');

alphabetMap.put('C','Cat');

system.debug('Map size:'+alphabetMap.size());

Output:


How to loop through map in order to get each element key and value in Apex Salesforce - Salesforce Globe For You

 How to loop through map in order to get each element key and value in Apex Salesforce  - Salesforce Globe For You 

Solution:First get list of keys of a map using Keyset() and then iterate over each key and use map.get(Key) to get value.

Example:

Map<String,String> alphabetMap = new Map<string,String>();

alphabetMap.put('A','Apple');

alphabetMap.put('B','Ball');

alphabetMap.put('C','Cat');

//iterate the map to get each element key and value

for(String alphabet:alphabetMap.keySet()) {

    System.debug('Key:'+alphabet+' Value:'+alphabetMap.get(alphabet));

}

Output:



System.NoAccessException: Apex approval lock/unlock api preference not enabled - Salesforce Globe For You

System.NoAccessException: Apex approval lock/unlock api preference not enabled  - Salesforce Globe For You 

Problem:when you try to use lock/unlock/lock status(isLocked) related methods of Approval class,you get the above error.

Example:run the below piece of code ,it will result in the above error if 'Enable record locking and unlocking in Apex' checkbox is false.

List<Lead> lstLead = new List<Lead>();

lstLead = [Select id,name from Lead For UPDATE];

System.debug('lstLead'+lstLead);

Map<Id,Boolean> recordMap = new Map<Id,Boolean>();

recordMap = Approval.isLocked(lstLead);

Solution:Enable the 'Enable record locking and unlocking in Apex' checkbox by navigating to Setup--> Create -->Process Automation Settings as shown in the image below.



Tuesday, September 1, 2020

Create Salesforce record using aura component Salesforce lightning - Salesforce Globe For You

 Create Salesforce record using aura component Salesforce lightning  - Salesforce Globe For You 

In this example,we will be creating form to create Lead Record.

Apex Class:

public class LeadCreationController {

    @AuraEnabled

    public static void createNewLead(Lead objLead) {

        insert objLead;

        system.debug('objLead:'+objLead);

    }

    @AuraEnabled

    public static Lead initializeLead() {

        Lead objLead = new Lead();

        system.debug('objLead:'+objLead);

        return objLead;

    }

}

LeadCreationForm.cmp

<aura:component controller="LeadCreationController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global">

    <aura:attribute name="newLead" type="Lead"/>

    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

    <div aria-labelledby="newLeadForm">

        <fieldset class="slds-box slds-theme--default slds-container--small">

            <legend id="newexpenseform" class="slds-text-heading--small 

                                               slds-p-vertical--medium">

                Create Lead

            </legend>

            <form class="slds-form--stacked">

                <lightning:input aura:id="firstName" label="First Name"

                                 name="FirstName"

                                 value="{!v.newLead.FirstName}"/>

                

                <lightning:input aura:id="lastName" label="Last Name"

                                 name="LastName"

                                 value="{!v.newLead.LastName}"

                                 required="true"/>

                

                <lightning:input aura:id="company" label="Company"

                                 name="Company"

                                 value="{!v.newLead.Company}"

                                 required="true"/>

                <lightning:button label="Create Lead" 

                                  class="slds-m-top--medium"

                                  variant="brand"

                                  onclick="{!c.createLead}"/>

            </form>

        </fieldset>

    </div>

</aura:component>

LeadCreationFormController.js

({

  doInit : function(component, event, helper) {

        

        var action = component.get("c.initializeLead");

        action.setCallback(this, function(response) {

            var state = response.getState();

            if (state === "SUCCESS") {

                console.log('Success');

              component.set("v.newLead", response.getReturnValue());

            }

        });

        $A.enqueueAction(action);

    },

    

    createLead : function(component, event, helper) {

        var action = component.get("c.createNewLead");

        action.setParams({

            objLead:component.get("v.newLead")

        });

        action.setCallback(this, function(response) {

            var state = response.getState();

            if (state === "SUCCESS") {

                console.log('Success');

                alert("Lead Record Created Successfully");

                var action1 = component.get("c.initializeLead");

                action1.setCallback(this, function(response) {

                    var state = response.getState();

                    if (state === "SUCCESS") {

                        console.log('Success');

                        component.set("v.newLead", response.getReturnValue());

                    }

                });

                $A.enqueueAction(action1);

                }

        });

        $A.enqueueAction(action);

    

  }

})

TestApp.app

<aura:application extends="force:slds">

  <c:LeadCreationForm/>

</aura:application>

Output:





Tuesday, August 25, 2020

How to change index of an element in an array (list) in aura component - Salesforce Globe For You

 How to change index of an element in an array (list) in aura component  - Salesforce Globe For You 

ChangeIndexOfAnElement.cmp

<aura:component >

    <aura:attribute name="fruits" type="List" default="['Mango','Apple','Orange','Kiwi']"/>

    <aura:attribute name="oldIndex" type="Integer"/>

    <aura:attribute name="newIndex" type="Integer"/>

    The available fruits are <br/>

    <aura:iteration items="{!v.fruits}" var="fruit" indexVar="index">

        {!index}) {!fruit}<br/>

    </aura:iteration>

    <br/>

    <lightning:input type="number" name="beforeIndex" label="Enter current Index" value="{!v.oldIndex}"/>

<lightning:input type="number" name="after Index" label="Enter new Index" value="{!v.newIndex}"/>

    <br/><lightning:button variant="brand" label="Change Index" title="Brand action" onclick="{!c.changeIndex}" />

</aura:component>


ChangeIndexOfAnElementController.js

({

changeIndex : function(component, event, helper) {

var oldIndex =component.get("v.oldIndex");

        var newIndex = component.get("v.newIndex");

        var fruits = component.get("v.fruits");

        if(newIndex >=fruits.length){

            var temp = newIndex - fruits.length+1;

            while(temp--){

                fruits.push(undefined);

            }

            

        }

        fruits.splice(newIndex,0,fruits.splice(oldIndex,1)[0]);

        component.set("v.fruits",fruits);

        

}

})

TestApp.app

<aura:application extends="force:slds">

<c:ChangeIndexOfAnElement/>

</aura:application>

Output:




How to display index of an element in a list in aura component - Salesforce Globe For You

 How to display index of an element in a list in aura component  - Salesforce Globe For You 

Solution:Use indexVar attribute of aura:iteration to display index of an element

Example:

IndexOfElement.cmp

<aura:component >

    <aura:attribute name="CricketPlayers" type="List" default="['Sachin','Kohli','Dhoni','Rohit']"/>

    The Cricket Players are <br/>

    <aura:iteration items="{!v.CricketPlayers}" var="player" indexVar="index">

        {!index+1}) {!player}<br/>

    </aura:iteration>

</aura:component>

TestApp.app

<aura:application extends="force:slds">

<c:IndexOfElement/>

</aura:application>

Output:


For loop in aura component or how to iterate a list in aura component - Salesforce Globe For You

 For loop in aura component  - Salesforce Globe For You 

ForLoop.cmp

<aura:component >

    <aura:attribute name="fruits" type="List" default="['Mango','Apple','Orange','Kiwi']"/>

    The available fruits are <br/>

    <aura:iteration items="{!v.fruits}" var="fruit" indexVar="index">

        {!index+1}) {!fruit}<br/>

    </aura:iteration>

</aura:component>


TestApp.app

<aura:application extends="force:slds">

<c:ForLoop/>

</aura:application>


Output:


Wednesday, August 19, 2020

Soql query to fetch list of lwc components - Salesforce Globe For You

 query lwc components  - Salesforce Globe For You 

Go to Developer console and click on 'Query Editor' tab and make sure the tooling API checkbox is clicked.


Use the following query to retrieve LWC components

Select id, masterLabel, apiVersion from LightningComponentBundle

Output:



Wednesday, August 5, 2020

How to query aura component Salesforce lightning - Salesforce Globe For You

How to query aura components  - Salesforce Globe For You 

Open anonymous window in developer console and execute the piece of code below.

List<AuraDefinitionBundle> lstAuraDefinitionBundle = new List<AuraDefinitionBundle>();
lstAuraDefinitionBundle = [SELECT Id, DeveloperName, apiVersion,description FROM AuraDefinitionBundle];
system.debug('lstAuraDefinitionBundle'+lstAuraDefinitionBundle);
Output:

Tuesday, August 4, 2020

How to display multiple tabs in aura component Salesforce lightning - Salesforce Globe For You

How to display multiple tabs in aura component  - Salesforce Globe For You 

Multiple tabs.cmp
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" access="global">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:attribute name="tabId" type="String" default="2"/>
    <aura:handler name="change" value="{!v.tabId}" action="{!c.handleTabChange}"/>
    <lightning:tabset aura:id="tabs" selectedTabId="{!v.tabId}">
        <lightning:tab label="Tab One" id="tab1">
           Tab One Content inside the tab
            <lightning:button label="Navigate To Next Tab" onclick="{!c.changeTab}" />
        </lightning:tab>
        <lightning:tab label="Tab Two" id="tab2">
            Tab Two Content inside the tab
            <lightning:button label="Navigate To Next Tab" onclick="{!c.changeTab}" />
        </lightning:tab>
        <lightning:tab label="Tab Three" id="tab3">
            Tab three Content inside the tab
            <lightning:button label="Navigate To Next Tab" onclick="{!c.changeTab}" />
        </lightning:tab>
    </lightning:tabset>
</aura:component>

MultipleTabsController.js

({
    doInit : function(component, event, helper) {
        component.find("tabs").set("v.selectedTabId", "tab1");
    },changeTab: function(component) {
        var currentTabId = component.get("v.tabId");
        if(currentTabId =='tab1') {
            component.set("v.tabId", "tab2");
        }
        if(currentTabId =='tab2') {
            component.set("v.tabId", "tab3");
        }
    },
    handleTabChange: function(component) {
        var selected = component.get("v.tabId");
        component.find("tabs").set("v.selectedTabId", selected);
    }
})

MultipleTabsApp.app
<aura:application extends="force:slds">
<c:MultipleTabs/>
</aura:application>

Output:

Friday, June 5, 2020

How to view full or complete system.debug logs in Salesforce - Salesforce Globe For You

How to view complete system.debug logs in salesforce?  - Salesforce Globe For You 

Problem: When we use system.debug in Apex methods for debugging and when we run that method,the debug log string gets truncated and displays half of the result sometimes.

Solution:you can view complete debug value using 'Open Raw Log' option in the logs tab of Developer console.
Example:

public class ViewCompleteJSONController {
    public static void viewJSON() {
        List<LeadWrap> lstLeadWrap = new List<LeadWrap>();
        For(Lead objLead:[Select id,name,company,status from Lead]) {
            LeadWrap objWrap = new LeadWrap();
            objWrap.name = objLead.name;
            objWrap.company = objLead.company;
            objWrap.status = objLead.status;
            lstLeadWrap.add(objWrap);
        }
        system.debug('Lead JSON:'+JSON.serialize(lstLeadWrap));
    }
    public class LeadWrap {
        public String name {get;set;}
        public String company{get;set;}
        public String status {get;set;}
    }
}

When we run the method in developer console using Debug --> Open Execute Anonymous Window

ViewCompleteJSONController.viewJSON();

The debug log gets display but string may appear as truncated.

To view complete string ,go to that logand right click,you will get the option to 'Open Raw Log' as shown in the image below.

Now,on click it,the debug log appears completely.

Enjoy

Tuesday, June 2, 2020

Display object names as picklist or drop-down in visual force page

Display object names as drop-down in visual force page.
Apex Class:

public class ObjectNameAsPicklistController {
    public List<SelectOption> lstObject {get;set;}
    public String selectedObject {get;set;}
    public ObjectNameAsPicklistController() {
        lstObject = new List<SelectOption>();
        for(String obj:schema.getGlobalDescribe().keyset()) {
            system.debug('obj:'+obj);
            lstObject.add(new selectOption(obj,obj));
        }
    }
    
}
Page:ObjectAPINameAsPicklist
<apex:page controller="ObjectNameAsPicklistController">
<apex:form>
    <apex:pageBlock>Select Object:<br/>
        <apex:selectList value="{!selectedObject}" label="Select Object:" title="Select Object:">
            <apex:selectOptions value="{!lstObject}"/>
        </apex:selectList>
    </apex:pageBlock>
</apex:form>
</apex:page>

Output:

Wednesday, April 15, 2020

How to delete multiple records at a time after verifing required data in each record salesforce

How to delete multiple records at a time after verifing required data in each record salesforce

Problem: I need to verify data in couple of fields of a record and then need to delete those records if data is not as expected.
If I need to open each record in salesforce and then delete one by one,it's very time consuming.
Solution: Open Developer Console and then go to Query Editor as shown in the image below.
In my scenario,I need to verify the lead records and then delete them.
So I wrote the following query and then click 'Execute' to display the results.
Select id,name,company from Lead
Now I can verify data in each record and then select the required records.Once records are selected,click on 'Delete Row' button to delete those records.

Sunday, April 12, 2020

Calculate your age or how old are you? - Salesforce Globe For You

Calculate Age:In order to know how old are you,please click the link below and check
Age Calculator

If you need code,please do comment or request the code through the contact form present at the right side of the page.

Monday, March 30, 2020

How to display account and its related contacts on selection in visualforce page

How to display account and its related contacts on selection in visualforce page
Apex Class:
public class DisplayContactOnAccountSelController {

    public list<AccountContactWrapper> lstAccountContactWrapper { get; set; }
    public list<AccountContactWrapper> lstSelectedAccountContactWrapper { get; set; }
    public list<account> selectedAccounts{get;set;}   

    public DisplayContactOnAccountSelController () {
        lstSelectedAccountContactWrapper = new list<AccountContactWrapper>();
        if(lstAccountContactWrapper == null) {
            lstAccountContactWrapper = new list<AccountContactWrapper>();
            for(account a:[select id,name,(select id,name from contacts) from account limit 10]) {
                lstAccountContactWrapper.add(new AccountContactWrapper(a));
            }
        }
    }
 
    public void ProcessSelected() {
        lstSelectedAccountContactWrapper =new list<AccountContactWrapper>();
        selectedAccounts =new list<Account>();
        for(AccountContactWrapper wrapobj:lstAccountContactWrapper){
            if(wrapobj.isSelected==true) {
                selectedAccounts.add(wrapobj.acc);
            } 
        }
       
        for(Account acc:[select id,name,(select id,name from contacts) from account where id in:selectedAccounts]) {
            lstSelectedAccountContactWrapper.add(new AccountContactWrapper(acc)); 
        }
             
    }
    public class AccountContactWrapper {
 
        public Account acc {get;set;}
        public boolean isSelected {get;set;}
   
        public AccountContactWrapper(account a) {
            acc = a;
            isselected=false;
        }
    }

}
Visualforce Page
<apex:page sidebar="false" controller="DisplayContactOnAccountSelController">
<apex:form >
    <apex:pageBlock id="AccountContactBlock">
        <apex:pageBlockSection columns="2">
        <apex:pageBlockTable value="{!lstAccountContactWrapper}" var="acc" id="AccountSection">
            <apex:column >
                <apex:inputCheckbox value="{!acc.isSelected}" id="InputId"/>
            </apex:column>
            <apex:column value="{!acc.acc.name}"/>
        </apex:pageBlockTable>
        <apex:pageBlockTable value="{!lstSelectedAccountContactWrapper}" var="acc" id="contactsSection" rendered="{!IF(lstSelectedAccountContactWrapper.size > 0,true,false)}">>
            <apex:column headerValue="Account and Its Related Contacts">
                <apex:pageBlockTable value="{!acc.acc.contacts}" var="con">
                    <apex:facet name="header">{!acc.acc.Name}</apex:facet>
                    <apex:column value="{!con.name}" headerValue="Contact Name"/>
                </apex:pageBlockTable>
            </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlockSection>
        <apex:pageBlockButtons location="bottom">
          <apex:commandButton action="{!ProcessSelected}" value="Show Account and its Contacts" reRender="AccountContactBlock,contactsSection"/>
        </apex:pageBlockButtons>
    </apex:pageBlock>
</apex:form>

</apex:page>
Output:





Tuesday, March 17, 2020

How to display random number in visualforce page

Apex Class: OneDigitRandomNumberController
public class OneDigitRandomNumberController {
    public Integer iRandomNumber {get;set;}
    public void generateOneDigitRandomNumber() {
        iRandomNumber = Integer.valueof((Math.random() * 10));
        System.debug('One Digit Random Number  is'+iRandomNumber);
    }
}

Visualforce Page:OneDigitRandomNumber
<apex:page controller="OneDigitRandomNumberController" action="{!generateOneDigitRandomNumber}">
<apex:form >
<b> One Digit Random Number: </b> {!iRandomNumber}<br/>
<apex:commandButton action="{!generateOneDigitRandomNumber}" value="Refresh"/>
</apex:form>
</apex:page>
Output:

Monday, March 9, 2020

Display Visualforce page Names as dropdown or picklist in visualforce Page

Display Visualforce page Names as dropdown or picklist in visualforce Page
ApexClass: DisplayVFNamesDropDownController
Public class DisplayVFNamesDropDownController {
    public String selectedVF {get;set;}
    public DisplayVFNamesDropDownController() {
    }
    public List<SelectOption> getVisualforcePages() {
        List<SelectOption> lstVFPage = new List<SelectOption>();
        lstVFPage.add(new SelectOption('' , 'Select'));
        for(ApexPage objPage:[Select id,name from ApexPage]) {
            lstVFPage.add(new SelectOption(objPage.Name , objPage.Name));
        }
        return lstVFPage;

    }
    public void getSelectedValue() {
       
    }
}
Visualforce Page: DisplayVFNamesDropDown
<apex:page controller="DisplayVFNamesDropDownController">
<apex:form >
    <apex:pageBlock >
        <apex:pageBlockSection >
            <apex:selectList value="{!selectedVF}" size="1" multiselect="false" onchange="{!SelectedValue}" >
                <apex:selectOptions value="{!VisualforcePages}" />
                <apex:actionSupport event="onchange" reRender="selectedPageId" action="{!getSelectedValue}"/>
            </apex:selectList>
        </apex:pageBlockSection>
        <apex:pageBlockSection id="selectedPageId">
            Selected Page: {!selectedVF}
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:form>
</apex:page>
Output:


Display data using Apex Maps in Visualforce Page - Salesforce Globe For You

Display data using Apex Maps in Visualforce Page  - Salesforce Globe For You 

Apex Code:  DisplayMapController
public class DisplayMapController {
    public Map<String,Account> mapAccount {get;set;}
    public DisplayMapController() {
        mapAccount = new Map<String,Account>();
        for(Account objAccount:[Select id,name,type,description from Account]) {
            mapAccount.put(objAccount.Id,objAccount);
        }
    }
}
Visualforce Page:DisplayMap

<apex:page controller="DisplayMapController">
<apex:form>
    <apex:pageBlock>
        <apex:pageBlockSection>
            <apex:pageBlockTable value="{!mapAccount}" var="acc">
                <apex:column value="{!mapAccount[acc].Name}"/>
                <apex:column value="{!mapAccount[acc].Type}"/>
                <apex:column value="{!mapAccount[acc].Description}"/>
            </apex:pageBlockTable>
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:form>
</apex:page>
Output:


Thursday, March 5, 2020

Retrieving Data from an Apex Controller - Salesforce Globe For You

Retrieving Data from an Apex Controller

To retrieve the string array from an Apex controller, bind the component to the controller. This component retrieves the string array when a button is clicked.

<aura:component controller="namespace.AttributeTypes">
    <aura:attribute name="countries" type="String[]" default="India, USA,Singapore, Germany"/>
    <aura:iteration items="{!v.countries}" var="s">
        {!s}
    </aura:iteration>
    <lightning:button onclick="{!c.getString}" label="Update"/>
</aura:component>






Set the Apex controller to return a List<String> object.



public class AttributeTypes {
    private final String[] arrayItems;
    
 @AuraEnabled
    public static List<String> getStringArray() {
        String[] arrayItems = new String[]{ 'Canada', 'Mexico', 'Austarlia' };
        return arrayItems;
    }

}


This client-side controller retrieves the string array from the Apex controller and displays it using the {!v.countriesexpression.

({
    getString : function(component, event) {
    var action = component.get("c.getStringArray");
     action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var stringItems = response.getReturnValue();
                component.set("v.countries", stringItems);
            }
        });
        $A.enqueueAction(action);
    }
})

To retrieve data from an object that’s returned by an Apex controller, create an attribute with a type corresponding to a standard or custom object.

<aura:attribute name="accounts" type="Account[]"/>