You need to sign in to do that
Don't have an account?

Help with if conditions in dynamic soql
String level ='Top'; String query='select id,Custompicklist__c from Contact'; if(Roleslist.size() >0){ for(Integer i =0; i<roles.size();i++){ if(i==0){ query +=' where account.Active__c=true and custompicklistfield__c=:level and roles__c INCLUDES (\''+roleslist[0]+'\''; }else{ query += ',\''+roleslist[i]+'\''; } } query += ')' limit 3; } c=database.query(query); THIS BRINGS CONTACT IDs of CONTACTS WHOSE LEVEL IS SET TO HIGH. BUT WHEN the field is set to a null or different value, then the query goes wrong and fetches 0 records.
As you are fetching contact records for which custompicklistfield__c is set to 'Top' and all other conditions in where clause are bind with AND connector, you will not get any contacts if custompicklistfield__c field is set to any other value except 'Top'.
You should reconstruct your condition based on which records you want.
You could play with the ORDER BY feature , but this would rely to some degree on what values are stored in the picklist (and i think nulls have fun in the sort column). If the picklist is something like "Top","Secondary","Tertiary" try the DESC key work to sort in reverse. Then as you do your write, test the custompicklist value in the loop.
Other options
1. If unable to get a Sort running over custompicklist field, create a formula field in the Contact record that is true / false = if (custompicklistfield__c ="Top",TRUE,FALSE) or perhaps a number value to sort the custompicklist values in an order that makes sense. Then query on that field and then loop the result and test the customepicklist value and write your values accordingly.
2. Do 2 x queries - one with custompicklist to Top ("Top Results") and other to collect all ("Full results"). Push them both to Maps, and as you loop the "full result" set, test the "Top" Map results for the key and drag the values from that "Top" Map, not your "Full" Map.
Regards
Andrew
Please mark it as best answer if this resolves your issue.
Regards,
Neha
Also use two different test methods to test these conditions as code will execute only one set of records at once.
You can post your test class code, if you still face issue.