function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Adam NilaAdam Nila 

Filter SOQL results by active user

What I want to do is pull a list of events scheduled for today but only list the events relevant to the active user.... Here's what I have so far...

 

public class QuickLogController {
    public String username{get;set;}
    
    public string finduser(){
		
        username = Userinfo.getUserName();
        return username;
    }  
    
    public list<event> getEventsToday(){
       
       List<event> TodaysEvents = Database.query (
           'SELECT Who.Name, Owner.id, Subject, StartDateTime, Location FROM event WHERE StartDateTime = TODAY AND Owner.Name = :username ');
        return TodaysEvents;
        	        
    }
    
}

When I run this without "AND Owner.Name = :username '" it works fine.  When I test it in the query editor and replace ":username" with my name, it works fine.  Not sure what I'm doing wrong here?
Best Answer chosen by Adam Nila
JeffreyStevensJeffreyStevens
okay - try this....
List<event> TodaysEvents = new list<event>([SELECT Ownerid FROM event WHERE StartDateTime = TODAY AND Ownerid = :UserInfo.getUserId()]);

that worked for me - then add the other fields as you need.

All Answers

JeffreyStevensJeffreyStevens
Try...

.... AND OwnerId =  :UserInfo.getUserId()
Adam NilaAdam Nila
Tried that as well... The code passes without any noted problems, but when I preview the page that's it presents me with the error "Unexpected token ("
JeffreyStevensJeffreyStevens
okay - try this....
List<event> TodaysEvents = new list<event>([SELECT Ownerid FROM event WHERE StartDateTime = TODAY AND Ownerid = :UserInfo.getUserId()]);

that worked for me - then add the other fields as you need.
This was selected as the best answer
Adam NilaAdam Nila
That did the trick.  Thank you!  Any chance you might be able to explain the difference between the two pieces of code pertaining to why ':UserInfo.getUserId()' worked with one but not the other?  From my obviously non-expert point of view they don't seem very different at all.   I've spent a few hours trying to figure this out with every other example I've looked at indicating it should work both the way I posted and the way you originally suggested.
JeffreyStevensJeffreyStevens
glad it worked.

I think because you were using the database.query() construct.  So, your SOQL was in quotes - basically a string.  So if you wanted to stay in the string - I think you'd have to do something like....

string SOQLString = 'SELECT Who.Name, Owner.id, Subject, StartDateTime, Location FROM event WHERE StartDateTime = TODAY AND OwnerId = \'' + :userInfo.getuserId() + '\'';

List<event> TodaysEvents = Database.query (SOQLString);

(althought I'm not sure how the TODAY would have worked in that code).