[SalesForce] Salesforce lightning get current users username

How I would go about getting the current users username or first and last name?

I have been looking at this for the last couple of hours – I was just wondering how I would go about getting their name and then displaying it on the page.

For example the current user is 'John Smith' and in the lightning component I want to output John Smith's name like:

Welcome to our community John Smith!

Best Answer

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);
     }
 })
Related Topic