This is the 2nd post in a series discussing some complex code we’ve written for recent projects. Our first post detailed performing a query using Dynamic SOQL. In that post, you had to hard-code the Contact fields that you wanted to query. This isn’t always ideal. Sometimes you want to query all fields on the object and you don’t want to edit your code each time you add a new field.
You can accomplish this task by using the field describe result’s getMap() method. Which returns a map of field names and field describe details. Don’t worry about the field describe details portion of the Map, for now we just want the Map’s keySet, which contains every field on the Contact object.
The below code adds to our post from last week, using the above concept to compile a string of field names to use in our SOQL query.
public class website_WebServices
{
//Function to perform Dynamic SOQL query on Contacts
public static <Contact> getContacts(String whereClause)
{
//Create a map from the results of a Describe of the Contact Object
Map<String, Schema.SObjectField> cFieldMap = Schema.SObjectType.Contact.fields.getMap();
//Generate a comma delimited String of Contact Fields
String conFields = '';
for ( String f : cFieldMap.keySet() )
{
conFields += f;
conFields += ',';
}
conFields = conFields.subString(0,conFields.Length() -1);
//Define an Order By clause to sort your query
String orderBy = ' Order By MailingState ';
//Define your entire Query as a string
String qryString = 'SELECT ' + conFields + ' FROM Contact ' + whereClause + orderBy + ' limit 10';
//Query salesforce with your Query string
List<Contact> queryResults = Database.query(qryString);
return queryResults;
}
//Sample Where Clause
public static String whereClause = 'WHERE Lastname != null ';
//Sample function to get a list of Contacts by passing the Where Clause to the getContacts function
public static list<contact> contacts = getContacts(whereClause);
}