Salesforce lightning get current users username
I wish there was concept like merge field in Lightning components where some functions were global and directly accessible but looks like only way to do this will be code with server side call.
Below is sample code
public with sharing class SimpleServerSideController {
//Use @AuraEnabled to enable client- and server-side access to the method
@AuraEnabled
public static String getUserName() {
return userinfo.getName();
}
}
<aura:component controller="SimpleServerSideController">
<aura:attribute name="Name" type="String"/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
</aura:component>
({
doInit: function(cmp){
var action = cmp.get("c.getUserName");
action.setCallback(this, function(response){
var state = response.getState();
if (state === "SUCCESS") {
cmp.set("v.Name", response.getReturnValue());
}
});
$A.enqueueAction(action);
}
})
We can make use of Lightning Data service to access any of the user fields on the Lightning component without need to use apex controller.
Example:
<aura:attribute name="currentUser" type="User"/>
<force:recordData aura:id="recordLoader" recordId="{!$SObjectType.CurrentUser.Id}" fields="Profile.Name" targetFields="{!v.currentUser}"/>
Access the value using the syntax: {!v.currentUser.Profile.Name}
We can fetch from email field if it is '[email protected] on user profile without server call.
Lightning Component :
<aura:component implements="flexipage:availableForRecordHome>
<aura:attribute name="UserName" type="String" default=""/>
</aura:component>
javaScript controller :
({ doInit : function(component, event, helper) {
var UserName = $A.get("$SObjectType.CurrentUser.Email");
cmp.set("v.UserName",(UserName.substring(0, UserName.lastIndexOf("@"))));
alert(cmp.get("v.UserName"));
}
})