Use Salesforce Data in Apex Code
We use SOQL to query a Salesforce org and use its data with our code. In this step, we use SOQL to get information about the product that we want to add as the bonus orderItem.
Add SOQL to Get Data from Salesforce
- In your class, under the comment
//TO DO 3.1
(near line 5), paste this code:
What are we doing here?
First, we use SOQL to get the ID and ProductCode for the bouquet product that has the product code BOT-BB-12
, and store the ID in a list called bonusProductList
. Then we check the number of items in bonusProductList
. If there is at least one value in the list, we define a new Product2 sObject, called bonusProduct
, and assign the first sObject in the bonusProductList
list to it.
Next, we use another SOQL query to get the ID of the PricebookEntry for the bonusProduct
. We store the PricebookEntry ID in a PricebookEntry list called entryList
.
Finally, we check the number of items in entryList
. If there is at least one value in the list, then we define a new PricebookEntry sObject, called entry
, and assign the first sObject in the entryList
list to it.
Use DML to Send Data to Salesforce
If you completed the Object-Oriented Programming for Admins module, you might remember that DML is the data manipulation language that we use to send data to a Salesforce org. As an admin, you know DML as the Insert (create a record), Update (edit a record), and Delete (delete a record) statements that you use with data manipulation tools, such as Data Loader.
We’ve created one or more free bouquets and added them to a list. But they exist only in Apex code. We haven’t saved anything to the Salesforce org. We use DML to do that.
- In your class, under the comment
//TO DO 3.2
, paste this code: - Under the comment
//TO DO 2.4
, remove the comment characters (//
) from the line that reads://PricebookEntryId = entry.id,
- Finally, we need to end the
if
statement (the code that runs if we determine we have a bonus bouquet).
In your class, under the comment//TO DO 3.3
, paste this code: - Save your class.
Now your class should look like this: