2

I have a SOQL query,

I want to check the fields in the query for FLS (Field Level Security) before building the query string, and if they aren't readable, dont add them to the string. This might not be the very best approach, but it's somewhere for me to start. The following works fine.

String soql = 'SELECT Id, MAX(Name) personName, MAX(From_Date__c) fromDate, MAX(Status__c) status' String end = ' FROM The_Object__c WHERE Id = :Id' soql += end SObject r = Database.query(soql); 

So to check the field before adding it to the string... Somthing like this perhaps: (which doesnt work)

String extra_soql = ', SUM(Revenue__c) revenue '; if (!Schema.sObjectType.The_Object__c.fields.Revenue__c.isAccessible()){ REMOVE THE SOQL SOMEHOW? OR PASS AN EMPTY STRING TO THE QUERY? extra_soql = ''; <-- DOESNT WORK extra_soql = ' '; <-- DOESNT WORK extra_soql = NULL; <-- DOESNT WORK NOT SURE WHAT TO DO IN HERE } soql += extra_soql soql += end SObject r = Database.query(soql); 

Any suggestions or advice would be greatly appreciated.

2
  • What is FSL? That TLA is not familiar to me. Commented Jun 20, 2014 at 16:42
  • 1
    Pretty sure @Daft meant FLS (Field Level Security) Commented Jun 20, 2014 at 17:59

2 Answers 2

2

You could try something like this:

Map<Schema.SObjectField, String> checkFields = new Map<Schema.SObjectField, String> { The_Object__c.Revenue__c => 'SUM(Revenue__c) revenue' // Add other field checks as necessary }; String[] queryFields = new String[] { 'Id', 'MAX(Name) personName', 'MAX(From_Date__c) fromDate', 'MAX(Status__c) status' }; for (Schema.SObjectField field : checkFields.keySet()) { if (field.getDescribe().isAccessible()) { queryFields.add(checkFields.get(field)); } } String soql = String.format( 'SELECT {0} FROM The_Object__c WHERE Id = :Id', new String[] { String.join(queryFields, ',') } ); 

In Summer '14 limits are removed on describe calls :)

1
  • This is a great solution, cheers!! Commented Jun 24, 2014 at 9:33
1

Why not something as simple as this?

I've reversed your if condition and removed the temporary extra_soql String.

if (Schema.sObjectType.The_Object__c.fields.Revenue__c.isAccessible()) { soql += ', SUM(Revenue__c) revenue ' } soql += end; SObject r = Database.query(soql); 

There are further examples in the documentation, although none of them use dynamic SOQL, but the fundamentals are the same.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.