Tag Archives: SFDC

Get Current User Info Using Apex in Salesforce

String FirstName = UserInfo.getFirstName();//Returns the context user's first name.
System.Debug('FirstName-' + FirstName);
String LastName = UserInfo.getLastName();//Returns the context user's last name.
System.Debug('LastName-' + LastName);
String Name = UserInfo.getName();//Returns the context user's full name.
System.Debug('Name-' + Name);
String UserEmail = UserInfo.getUserEmail();//Returns the current user’s email address.
System.Debug('UserEmail-' + UserEmail);
String UserType = UserInfo.getUserType();//Returns the context user's type.
System.Debug('UserType-' + UserType);
String UserId = UserInfo.getUserId();//Returns the context user's ID.
System.Debug('UserId-' + UserId);
String UserName = UserInfo.getUserName();//Returns the context user's login name.
System.Debug('UserName-' + UserName);
String ProfileId = UserInfo.getProfileId();//Returns the context user's profile ID.
System.Debug('ProfileId-' + ProfileId);
String UserRoleId = UserInfo.getUserRoleId();//Returns the context user's role ID.
System.Debug('UserRoleId-' + UserRoleId);
String SessionId = UserInfo.getSessionId();//Returns the session ID for the current session.
System.Debug('SessionId-' + SessionId);
TimeZone tz = UserInfo.getTimeZone();//Returns the current user’s local time zone.
System.Debug('TimeZone-' + tz);
String DefaultCurrency = UserInfo.getDefaultCurrency();//Returns the context user's default currency code for multiple currency organizations or the organization's currency code for single currency organizations.
System.Debug('DefaultCurrency-' + DefaultCurrency);
String Language = UserInfo.getLanguage();//Returns the context user's language.
System.Debug('Language-' + Language);
String Locale = UserInfo.getLocale();//Returns the context user's locale.
System.Debug('Locale-' + Locale);
String OrganizationId = UserInfo.getOrganizationId();//Returns the context organization's ID.
System.Debug('OrganizationId-' + OrganizationId);
String OrganizationName = UserInfo.getOrganizationName();//Returns the context organization's company name.
System.Debug('OrganizationName-' + OrganizationName);

How to cover pagereference method in test class

For Custom Controller


//Page reference to your VF Page
PageReference pageRef = Page.TestPage;
Test.setCurrentPage(pageRef);

//Pass necessary parameter
pageRef.getParameters().put('Id',id); 

//init controller 
CustomCtrl objCtrl = new CustomCtrl();

//Call pageRef mymethod
PageReference objPageRef = objCtrl.mymethod();

//Put system asserts
System.assertEquals (null,pageRef);

For Standard Controller

//First create record
Account acc = New Account();
acc.Name = 'Test Account';
INSERT acc;

//Page reference to your VF Page
PageReference pageRef = Page.TestPage;
Test.setCurrentPage(pageRef);

//Pass necessary parameter
pageRef.getParameters().put('Id',acc.id);   

//Pass your object to controller     
ApexPages.StandardController stc = new ApexPages.StandardController(acc);

//Call controller
CustomCtrl objCtrl = new CustomCtrl(stc);

//Call pageRef mymethod
PageReference objPageRef = objCtrl.mymethod();

//Put system asserts
System.assertEquals (null,pageRef);

Open a visualforce page in same primary tab by closing the current primary tab in Salesforce console

{!REQUIRESCRIPT(“/support/console/36.0/integration.js”)}
{!REQUIRESCRIPT(“/soap/ajax/36.0/connection.js”)}
try {
sforce.console.getEnclosingPrimaryTabId(function (result)
{
sforce.console.openPrimaryTab(result.id, ‘/apex/CaseSummary?id={!Case.Id}’, true);
});
}
catch(ex){
alert(‘An Error has Occured. Error:’ + ex);
}

Dynamic Getting sObject Picklist Values on Lightning Component

In this example we will fetch Picklist field “Industry” values from “Account” object and set in ui:inputSelect on Lightning Component.

Apex Class:

public class GetPicklistValuesController {
    @AuraEnabled
    public static List <String> getPicklistValues(sObject obj, String fld) {
        
        List <String> pList = new list <String>();
        
        //Get the object type of the SObject.
        Schema.sObjectType objType = obj.getSObjectType();

        //Describe the SObject using its object type.
        Schema.DescribeSObjectResult objDescribe = objType.getDescribe();

        //Get a map of fields for the SObject
        Map<String, Schema.SObjectField> fieldMap = objDescribe.fields.getMap();

        //Get the list of picklist values for this field.
        List<Schema.PicklistEntry > values = fieldMap.get(fld).getDescribe().getPickListValues();

        //Add these values to the selectoption list.
        for (Schema.PicklistEntry a: values) {
            pList.add(a.getValue());
        }
        pList.sort();
        return pList;
    }
}

Component:

<!--TestComponent-->
<aura:component controller="GetPicklistValuesController" access="global" implements="force:appHostable">
    <aura:attribute name="objInfo" type="account" default="{sobjectType : 'Account'}" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>    
    <div class="slds-form-element">
        <label class="slds-form-element__label" for="select-01">Select Industry</label>
        <div class="slds-select_container">
            <ui:inputSelect  aura:id="accIndustry" class="slds-select"  change="{!c.onPicklistChange}"/>
        </div>
    </div>
</aura:component>

Component Helper:

({
    fetchPickListVal: function(component, fieldName, elementId) {
        var action = component.get("c.getPicklistValues");
        action.setParams({
            "obj": component.get("v.objInfo"),
            "fld": fieldName
        });
        var opts = [];
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state == "SUCCESS") {
                var allValues = response.getReturnValue();
                
                opts.push({
                    class: "optionClass",
                    label: "--- None ---",
                    value: ""
                });
                for (var i = 0; i < allValues.length; i++) {
                    opts.push({
                        class: "optionClass",
                        label: allValues[i],
                        value: allValues[i]
                    });
                }
                component.find(elementId).set("v.options", opts);
            }
        });
        $A.enqueueAction(action);
    },
})

Component Controller:

({
    doInit: function(component, event, helper) {
        helper.fetchPickListVal(component, 'Industry', 'accIndustry');
    },
    onPicklistChange: function(component, event, helper) {
        //get the value of select option
        alert(event.getSource().get("v.value"));
    },
})

Lightning App:

<!--TestApp-->
<aura:application extends="ltng:outApp" access="global">
    <c:TestComponent />
</aura:application>

Output:

How to open a new Tab using PageReference in apex class?

We can use apex:commandLink to redirect a visualforce page in a new Tab URL using PageReference in apex class.

Sample Code:

VF Page:

<apex:page controller="SampleleRedirect">
	<apex:form >
		<apex:pageblock >
			<apex:commandlink action="{!redirect}" target="_blank">
				<apex:commandButton value="Open in New Tab"/>
			</apex:commandLink>
		</apex:pageblock>
	</apex:form>
</apex:page> 

Apex Controller:

public class SampleleRedirect {   

	public SampleleRedirect() {
	
	}

	public pageReference redirect() {
		PageReference pageRef = new PageReference('http://www.biswajeetsamal.com');
		pageRef.setRedirect(true);
		return pageRef;
	}            
}