0

I want to return all Users which match the Name and Title arguments I pass into my method. If the Name and Title arguments I pass in are empty, I would like to return all Users.

For example, if the Name I pass in is John Smith and the Title is Manager, I would like to return all John Smiths who are Managers. This works fine right now, but it's when I leave both fields blank, I have a problem.

At the moment, if Name and Title arguments I pass in are empty, my method is only returning Users who have a Name and Title, as opposed to Users who may have a Name but no Title.

@RemoteAction
public static Object searchForUsers(String name, String title) {

String soql = 'SELECT Id,Name,Title,UserType' +
                                        ' FROM user WHERE  IsActive = true ' +
                                        ' and (FirstName like \'' + name + '%\'' +
                                        ' or LastName like \'' + name + '%\')' +
                                        ' and Title like \'' + title + '%\'' + 
                                        ' and UserType = \'Standard\'  ' +
                                        ' ORDER BY Name ASC  LIMIT 201';

return SOQLQueryFLS.query(soql);
}

I suppose I could just wrap my query in an if statement and have a second query to accommodate both fields being empty, but I would like to know if I can just update my existing query in some way.

2

Based on condition, prepare the where clause dynamically like below:

@RemoteAction
public static Object searchForUsers(String name, String title) {

    String soql = 'SELECT Id,Name,Title,UserType' +
        ' FROM user WHERE  IsActive = true ' + 
        ' and UserType = \'Standard\'';

    // add condition to query when name and title are not empty
    if(String.isNotEmpty(name) && String.isNotEmpty(title)) {
        soql += ' and (FirstName like \'' + name + '%\'' +
            ' or LastName like \'' + name + '%\')' +
            ' and Title like \'' + title + '%\'' + 
            ;
    }

    soql += ' ORDER BY Name ASC LIMIT 201';
return SOQLQueryFLS.query(soql);
}
| improve this answer | |
  • Cheers @Daft, happy coding! – Raul Sep 20 '17 at 10:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.