Andres Canavesi photo

javaniceday.com

Software development blog. Java, Node JS, Salesforce among other technologies

Migrate $User, $Profile, $Label and $Api to Lightning Components


Posted on Jun 18, 2020


Featured image
We can’t use $User, $Profile, $Label, and $Api in Lightning. We need to implement a server-side solution. Original JS button

alert($User.Email)
Create a Lightning component: JSMUserInfo.cmp

<aura:component implements="force:lightningQuickAction" controller="JSMUserInfoService" >
  <aura:attribute name="user" type="JSMUserInfo" />
  <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
 
  Id: {!v.user.Id}
  <br/>
  First name: {!v.user.FirstName}
  <br/>
  Last name: {!v.user.LastName}
  <br/>
  Email: {!v.user.Email}
 
</aura:component>

JSMUserInfo.js


({
  doInit : function(component, event, helper) {
    var action = component.get("c.getUserInfo");
    action.setCallback(this, function(response) {
      var state = response.getState();
      if(state == "SUCCESS" && component.isValid()){
        console.log("success") ;
        var result = response.getReturnValue();
        console.log(result);
        console.log(result.FirstName);
        component.set("v.user", result);
 
   }else{
     console.error("fail:" + response.getError()[0].message); 
    }
   });
  $A.enqueueAction(action);
}
})

A wrapper class containing the user info we need


public class JSMUserInfo{
  @AuraEnabled
  public String Id {get;set;}
  @AuraEnabled
  public String FirstName {get;set;}
  @AuraEnabled
  public String LastName {get;set;}
  @AuraEnabled
  public String Email {get;set;}
}

The server-side controller that exposes the User’s info


public class JSMUserInfoService {
 
@AuraEnabled
public static JSMUserInfo getUserInfo(){
  try{
    JSMUserInfo info = new JSMUserInfo();
    info.Id = Userinfo.getUserId();
    info.FirstName = Userinfo.getFirstName();
    info.LastName = Userinfo.getLastName();
    info.Email = Userinfo.getUserEmail();
    return info;
  }catch(Exception e){
     throw new AuraHandledException(e.getMessage()); 
  }
 
  } 
}

We can use a similar approach for $Api or any other global variable

$Profile


@AuraEnabled
public static Profile getProfileInfo(){
  try{
    String profileId = UserInfo.getProfileId();
    Profile profile = [SELECT Id, Name FROM Profile WHERE Id =:profileId];
    return profile;
  }catch(Exception e){
    throw new AuraHandledException(e.getMessage()); 
  }
}

$Site


@AuraEnabled
public static JSMSiteInfo getSiteInfo(){
  try{
    JSMSiteInfo info = new JSMSiteInfo();
    info.Prefix = Site.getPathPrefix();
    info.Domain = Site.getDomain();
    info.Name = Site.getName();
    return info;
  }catch(Exception e){
    throw new AuraHandledException(e.getMessage()); 
  }
}

Photo by Clark Young on Unsplash


dev
Search
Side Widget
You can put anything you want inside of these side widgets. They are easy to use, and feature the new Bootstrap 4 card containers!