[SalesForce] Get current user full name and id in Javacript page

In my application that uses JS the user can click a button to create a new record, the goal is to give them a column in a table where they can select an active user to assign the record to. So i built a remote action that queries all the active users into a list and then the JS functions take over and that list is now searchable in this field which works great.

Example:

 @RemoteAction
public static List<User> getActiveUsers() {

    String query = 'SELECT Id, FirstName, LastName FROM User WHERE IsActive = TRUE';
    return Database.query(query);
}   

Example:

<tr>
 <td>Owner</td>
 <td>
  <input type="text" class="form-control" ng-model="selectedOwner" placeholder="Type Owner Name"
         bs-options="user as user.FirstName + ' ' + user.LastName for user in userCollection | filter:$viewValue" bs-typeahead required/>
</td>

Now I want to take it one step further that when the page is first loaded the default is the current user.

So this makes me think I need another remote action to get the current user's information.

Example:

@RemoteAction
public static List<User> getCurrentUser() {
    String query = 'SELECT id, FirstName, LastName FROM User WHERE Id = $User.Id';
    return Database.query(query);
}

This compiles and lets me save however, when I run it through anonymous apex to see if a result returns I get the error:

no viable alternative at character '$'

Is this the right way to do this?

Best Answer

You can just merge the $User global variables into your markup:

var runningUserId = "{!$User.Id}"

Or you can use UserInfo methods in Apex. Don't use dynamic queries unless static queries won't work for you.

@RemoteAction
public static User getCurrentUser()
{
    return [SELECT Id, Name FROM User WHERE Id = :UserInfo.getUserId()];
}
Related Topic