• Home
  • About
    • Leadership
    • Partners
    • Blogroll
  • Force-Squared Blog
    • Tips and Tricks
    • Configuration
    • Development
  • Support
    • Knowledge Base
    • Submit a Case
  • Is It Dreamforce Yet?

X-Squared On Demand

Salesforce solutions delivered

  • Home
  • About
    • Leadership
    • Partners
    • Blogroll
  • Force-Squared Blog
    • Tips and Tricks
    • Configuration
    • Development
  • Support
    • Knowledge Base
    • Submit a Case
  • Is It Dreamforce Yet?
  • Tips and Tricks
  • Configuration
  • Development
You are here: Home / Lightning / Lightning Components / Lightning Component With Running User Information

Lightning Component With Running User Information

February 27, 2015 by David Schach 4 Comments

Last week, at Snowforce in Salt Lake City, I saw a demonstration of the Lightning App Builder and decided that I wanted to make a Lightning component of my own. I thought the best thing to do was to follow the quick-start PDF, and was quite proud of that. I made the text say "Hello David!" which seemed like a good start. Mike Gerholdt then challenged me to render the word "David" dynamically, pulling from the running user. I checked the documentation, and there is no $User global variable as there is in Visualforce, so I was faced with a conundrum: How to pull fields from the current User record? The documentation and quick-start expenses app show how to pull a list of records and then to choose one from those, but I wanted something different. After perusing Reid Carlberg's post about Lightning components, I had my answer. I won't explain too much what is going on here, but I will share the necessary parts of the app. I have endeavored to make all the method and variable names different enough so you can see where each comes from. If there is any confusion, please leave a comment and I will update the post accordingly. ExampleApp - Lightning Application This is only necessary for previewing your work in a browser window. As we will see, it is unnecessary for creating components for either the Salesforce1 mobile interface or the Lightning App Builder interface.

    

TopLevelUserComponent - Lightning Component This is perhaps the most important part, as it is a container for all the other components that will contain whatever we want to put in our application. This contains the required code for exposing the component to Salesforce1 (force:appHostable) and to the Lightning App Builder (flexipage:availableForAllPageTypes). If we put any code or styling here, it would be available, should we wish, to all child components. This is how components communicate with each other if they are not above or below in the component hierarchy. This is also important because apps will likely have multiple components all at the same hierarchy level, so the "top level" container allows us to unify everything in one place.

    

Hello TopLevelUserComponent!

UserFromUser - Lightning Component Here is where things get interesting. The component is fairly simple, with an Apex controller to allow us to pull data from the Salesforce database, an attribute for the running User, a line to run the code to query the data, and an output of that data.

    

User from User Component

User lastname: {!v.runningUser.LastName} User firstname: {!v.runningUser.FirstName}
Please note that I have written the first and last names thrice: Once with a ui:outputText tag, once as naked markup, and once with an aura:text tag. I have no idea which is the best practice, but as I try never to put naked text on a Visualforce tag, I will assume that either ui:outputText or aura:text are best. UserFromUser - Component JavaScript Controller This JavaScript class (I'm not sure if class is the right word, but it will have to do for now) contains the run-once code for this component. If we had code that would be run repeatedly, it would be better to put that into the Helper class. Because we have none, I did not put anything in the helper.
({
    doInit: function(component, event, helper) {
        var action = component.get("c.getCurrentUser"); // method in the apex class
        action.setCallback(this, function(a) {
            component.set("v.runningUser", a.getReturnValue()); // variable in the component
        });
        $A.enqueueAction(action);
    }
})
This shows the standard base-code that I plan to use for my components: Much as there is an action tag in the apex:page Visualforce component, which calls an Apex method, here I use the c.doInit action, which is prefaced by c to show that it is called in a controller (and as we will see below, that refers here to the JavaScript controller, whereas in JavaScript it refers to the Apex controller). CurrentUserController - Apex Controller This Apex class allows us to query the database. Note that the method is static and has the @auraenabled annotation, allowing it to be seen by the JavaScript controller. I have kept the code simple; were I to do this for an ISV, I might describe the User sObject and then included all available fields in my query. Here, though, I just wanted first and last names.
public class CurrentUserController {

    @AuraEnabled
    public static User getCurrentUser() {
    	User toReturn = [SELECT Id, FirstName, LastName FROM User WHERE Id = :UserInfo.getUserId() LIMIT 1];
        return toReturn;
    }
}
The method getCurrentUser is called as c.getCurrentUser in the JavaScript. The c refers to controller, and to a different controller, depending on where it is used. Style documents I could have styled the h1 tag in any of the components I used, as well as the Application. While I don't think that styling in the Application is a good idea for any uses that I can imagine right now, I do think that care should be taken in choosing whether to style in the top-level component or a lower-level one. The Java developer in me thinks that much as we control access by declaring variables as finely as possible, we should handle styling in the same way. This is the CSS that I used. I put it in the UserFromUser Style document.
.THIS h1 {
    font-size: 24px;
    padding-left: 40px;
}
For more information
  • Lightning Dev Guide
  • Trailhead Lightning Module
  • Configure Components for Lightning Pages and the Lightning App Builder
  • Salesforce Lightning Component Newbie Notes
  • Jeff Douglas: Building Your First Lightning Component

Share this:

  • Click to share on X (Opens in new window) X
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on Pocket (Opens in new window) Pocket
  • Click to email a link to a friend (Opens in new window) Email

Related

Filed Under: Apex, Lightning, Lightning Components, Lightning Platform, Salesforce CRM Tagged With: AppBuilder, Lightning, Salesforce1

← ChatterBINGO is Now Open-Source Duplicate Record Item Enrichment and Auto-Deletion Code →

Comments

  1. Brian says

    November 3, 2015 at 09:51

    David,

    Thanks for putting together this blog article. The example you used pretty much fit my exact use case and was able to help me understand what was going on without having to spend a few hours reading through The Lightning Components Developer Guide.

    Reply
  2. Eduardo Offermann Palma says

    November 5, 2015 at 17:56

    Hi David,

    Thank you for posting this. Could you please help me to find out a way to use the lighting styles component in a visualforce page?. I am showing up a lighting datepicker into a regular VF page but it looks bad.

    https://mrkr.io/JoeLbLeNPd

    And I want to that see like:

    https://mrkr.io/6P5lv1Ckqk

    My VF page is this:

    $Lightning.use(“c:GeneralApplication”, function() {
    $Lightning.createComponent(“c:GeneralComponent”,
    { label : “Press Me!” },
    “lightingComponent”,
    function(cmp) {
    });
    });

    The aura component:

    What can I do?

    Thank you!

    Reply
    • David Schach says

      November 23, 2015 at 19:25

      Thanks for the comment. To make the lightning styles show on your VF page, check out the Salesforce Lightning Design System. There is full documentation there.

      Reply
  3. Drew says

    April 28, 2016 at 14:14

    David,
    Thanks for putting this code example together, it’s exactly what I needed as a newbie to SF development. I have the controller working how I want in the sandbox, but now I need to deploy the CurrentUserController into production and write a simple test class for it. I’ve got the test class started, but something is not quite right, because the dev console tests are not showing that it’s calling the controller and reading through the lines of code. Could you help point out what I’m missing in the code below:

    @isTest
    public class CurrentUserControllerTestClass {
    static testMethod void validateCurrentuser() {
    CurrentUserController controller = new CurrentUserController();
    controller = new CurrentUserController();
    }
    }

    Reply

Share Your ThoughtsCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Find Us Online

  • Twitter
  • Facebook
  • LinkedIn
  • RSS

Subscribe

RSS Feed Comments

Subscribe via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 164 other subscribers

Copyright © 2008–2025 X-Squared On Demand · Genesis Framework by StudioPress · WordPress · Log in