0

In a vf controller, I'm trying to pass a string and a set into a query that goes to a map. I can't seem to get both the set and the string into the same line. Example:

private Boolean ValidateContacts(Set<Id> contactIdSet)
{
    String whereText;

    if(
    corpId != null
    )
    whereText = 'Account.Corporate_Account__c = \'' + objOpprtunity.Parent_Account__r.Corporate_Account__c + '\'';
    else {
    whereText = 'AccountId = \'' + objOpprtunity.Parent_Account__c + '\'';
    }

    Map<Id, Contact> inValidContacts = new Map<Id, Contact>([SELECT Id, Name FROM Contact WHERE Id IN :contactIdSet AND whereText]);

If I do :whereText it errors saying

Unexpected token ':'

If I do whereText it errors saying

Unexpected token ']'

Where am I going wrong?

2 Answers 2

4

You cannot use dynamic string in static Querry (Query inside square Bracket)

You have to use Database.query.

List<String> contactIdSet = new List<String>{'003123456789632145'};
String whereText = 'AccountId!=null';
String initialQuery ='SELECT Id, Name FROM Contact WHERE Id IN :contactIdSet AND ';
Map<Id, Contact> inValidContacts = new Map<Id, Contact>((List<Contact>)Database.query(initialQuery+whereText));

Src: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dynamic_soql.htm

1

Dynamic filters means you need to use Database.query. The following should work:

Map<Id, Contact> inValidContacts = new Map<Id, Contact>(
  (Contact[])Database.query(
    'SELECT Id, Name FROM Contact WHERE Id IN :contactIdSet AND ' +whereText
  )
);

This presumes that your filters are otherwise correct.

You must log in to answer this question.

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