Create SOQL to Return Data to Apex
Create a SOQL query to retrieve the Recruiting Account record that you created.
- In the Developer Console, click File | Open Resource.
- Select Account.obj and then click Open.
- Select Id and Name. Use CTRL (in Windows) or CMD (on a Mac) to select multiple fields.
- Click Query.
- If the Query Editor displays instructions for building a query, click Query again.
- At the end of the query, type
WHERE Name = 'Recruiting'
. - Verify that your SOQL query reads:
SELECT Id, Name FROM Account WHERE Name = 'Recruiting'
- Click Execute to execute the query and display the results.
To associate the newly created Contact with the Recruiting Account, add the SOQL query to the createContact method.
- In the CreateContactFromCan class, replace the existing code with this code:
public with sharing class CreateContactFromCan {
//Declare a method that returns void and accepts a Candidate list named candsFromTrigger public static void createContact (List<Candidate__c> candsFromTrigger){
//Select the Recruiting account from the database and add it to a list //named candAccts (from the Account class) List <Account> candAccts = [SELECT Id, Name FROM Account WHERE Name = 'Recruiting'];
//Instantiate a Contact list named conList List<Contact> conList = new List<Contact>();
//Declare a FOR list loop that uses an iteration variable named currentCandidate //to loop through the candsFromTrigger list for(Candidate__c currentCandidate:candsFromTrigger){
//Create a Contact and add it to conList //Set the FirstName, LastName, and Email attributes to match the //corresponding attributes of the currentCandidate object (First_Name__c, //Last_Name__c, and Email__c) conList.add(new Contact (AccountId = candAccts[0].id, FirstName = currentCandidate.First_Name__c, LastName = currentCandidate.Last_Name__c, Email = currentCandidate.Email__c) ); }
//Save conList to the database Database.insert(conList); } } - Save the CreateContactFromCan class.