2

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?

3

1 Answer 1

4

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()];
}
1
  • That's solid advice. Commented Jun 21, 2017 at 18:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .