Get Current User Id in Salesforce

How to get Current Logged in user Id in Apex, Visualforce, Lightning Component and Formula fields in Salesforce

Quick Code Snippets of how to get Current logged in user ids in Salesforce

Apex

System.debug('Current User Id - '+UserInfo.getUserId());

Visualforce

<apex:page>
  <h1>Visualforce Page</h1> 
   <p>UserId: {!$User.Id}</p>
   <p>User Email: {!$User.Email}</p>
</apex:page>

Aura Component

let currentUser = $A.get("$SObjectType.CurrentUser.Id");
Console.log(currentUser);

Lightning Web Components

Using wire

import USER_ID from '@salesforce/user/Id';
import NAME_FIELD from '@salesforce/schema/User.Name';
import EMAIL_FIELD from '@salesforce/schema/User.Email';

Formula Fields

$User.Id

Get Picklist Values in Apex

Author posted by Jitendra on Posted on under category Categories Salesforce and tagged as Tags , , with Leave a comment on Get Picklist Values in Apex

Code snippet of reading Picklist values in Salesforce Apex

In Interview question part 4, we discussed how dynamic Apex can be used to retrieve metadata information about Objects or fields on Object.

While writing highly configurable code, there are situation where we want to avoid hardcoding picklist values and read it realtime from field.

Below code snippet takes two parameter, Object and picklist field name. On basis of these two inputs, we can read either Picklist label or Picklist value (API Name)

String objectName = 'Contact';
String fieldName ='LeadSource';
  
Schema.SObjectType s = Schema.getGlobalDescribe().get(objectName) ;
Schema.DescribeSObjectResult r = s.getDescribe() ;
Map<String,Schema.SObjectField> fields = r.fields.getMap() ;
Schema.DescribeFieldResult fieldResult = fields.get(fieldName).getDescribe();
List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
for( Schema.PicklistEntry pickListVal : ple){
    System.debug(pickListVal.getLabel() +' '+pickListVal.getValue());
}