Dynamic SOQL and SOSL

,

As repeatedly emphasized in this book, good Force Platform applications are data-driven. These applications naturally interact with data, even to the point of sometimes changing the user interface based on data values, such as with record types, dependent picklists, or the Visualforce example you will be creating in the next chapter.

All these examples use different data, but rely on a fixed set of data structures. What about those times when you want to go beyond the data structure of a single known object? What if you want to create some functionality that can operate on different objects, depending on application context?

To address this issue, Apex code includes the ability to create SOQL and SOSL statements dynamically, where the actual query statements are not determined until run-time. You can also use dynamic DML statements to use put and get methods, followed by the field name and a value, to write values to variable fields in an object.

For dynamic SOQL, use the query() method on the Database object to specify a SOQL query at runtime. For dynamic SOSL, use the query() method on the Search object. For both of these approaches, use Apex describe calls to retrieve information about the objects and fields in your Force Platform data store, insuring that the query strings submitted are valid at run-time.

Using dynamic queries in your applications opens up a whole new world of opportunities, but this capability must include checks to insure that the results fall within acceptable bounds. Because of this need, use standard, data-driven Apex scripts when possible, and move into the area of dynamic SOQL or SOSL only when this feature can uniquely solve your application challenges.

Voice of the Developer

Take care not to jump to dynamic SOQL too quickly. You may believe that you need absolute flexibility in using fields and objects, but frequently this belief masks a reality that calls for loads of flexibility in selection criteria and a manageable flexibility in the sources of data.


For more information about using dynamic SOQL and SOSL, please refer to the Apex Language Reference documentation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.100.205