Apex Basics & Database

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Apex supports the following data types:

Primitive sObject Collections Typed list of values User-defined and system-supplied Apex classes

Data Manipulation Language (DML)

Provides a straightforward way to manage records by providing simple statements to insert, update, merge, delete, and restore records

Ex: return all accounts whose name is SFDC Computing and have more than 25 employees

SELECT Name, Phone FROM Account WHERE (Name='SFDC Computing' AND NumberOfEmployees>25)

Ex: use the targetDepartment variable in the WHERE clause

String targetDepartment = 'Wingo'; Contact[ ] techContacts = [SELECT FirstName,LastName FROM Contact WHERE Department=:targetDepartment];

Array Syntax for Declaring Color Variable

String[] colors = new List<String>();

Why are lists easier than arrays?

You aren't required to determine ahead of time how many elements you need to allocate

Syntax of a SOQL for loop:

for (variable : [soql_query]) { code_block } or for(variable_list : [soql_query]) { code_block }

The Apex class must be called ContactSearch and be in the public scope The Apex class must have a public static method called searchForContacts The method must accept two incoming strings as parameters The method should then find any contact that has a last name matching the first string, and mailing postal code (API name: MailingPostalCode) matching the second string The method should finally return a list of Contact records of type List that includes the ID and Name fields

public class ContactSearch { //its dont execute on developer console becose of static keyword try to remove static and run on developer console __public static List<Contact> searchForContacts(String lastName, String mailingPostalCode) { ____List<Contact> conList = [SELECT Id, Name, LastName, MailingPostalCode FROM Contact WHERE LastName = :lastName AND MailingPostalCode = :mailingPostalCode]; __return conList; _} }

Create an Apex class with a method that returns an array (or list) of formatted strings ('Test 0', 'Test 1', ...). The length of the array is determined by an integer parameter. The Apex class must be called StringArrayTest and be in the public scope The Apex class must have a public static method called generateStringArray The generateStringArray method must return an array (or list) of strings The method must accept an incoming Integer as a parameter, which will be used to determine the number of returned strings The method must return a string value in the format Test n where n is the index of the current string in the array

public class StringArrayTest { public static List<String> generateStringArray(Integer n) { List<String> myArray = new List<String>(); for(Integer i=0;i<n;i++) { myArray.add('Test ' +i); System.debug(myArray[i]); } return myArray; } }

Ex: insert contacts in bulk by inserting a list of contacts in one call -the sample then updates those contacts in bulk too

// Create a list of contacts List<Contact> conList = new List<Contact> { __new Contact(FirstName='Joe',LastName='Smith',Department='Finance'), ____new Contact(FirstName='Kathy',LastName='Smith',Department='Technology'), ____new Contact(FirstName='Caroline,LastName='Roth',Department='Finance'), ____new Contact(FirstName='Kim',LastName='Shain',Department='Education')}; // Bulk insert all contacts with one DML call insert conList; // List to hold the new contacts to update List<Contact> listToUpdate = new List<Contact>(); // Iterate through the list and add a title only // if the department is Finance for(Contact con : conList) { __if (con.Department == 'Finance') { ____con.Title = 'Financial analyst'; ____// Add updated contact sObject to the list. ____listToUpdate.add(con); __} ) // Bulk update all contacts with one DML call update listToUpdate;

Ex: add the Acme account to Salesforce -account sObject is created first -then passed as an argument to the insert statement (persists the record in Salesforce)

// Create the account sObject Account acct = new Account(Name='Acme', Phone='(415)555-1212', NumberOfEmployees='100'); // Insert the account by using DML insert acct;

Ex: upsert updates an existing contact record and inserts a new contact in one call

// Insert the Josh contact Contact josh = new Contact(FirstName='Josh',LastName='Kaplan',Department='Finance'); insert josh; //Josh's record has been inserted //so the variable josh has now an ID //which will be used to match the records by upsert josh.Description = 'Josh/'s record has been updated by the upsert operation.'; // Create the Kathy contact, but don't persist it in the database Contact Kathy = new Contact(FirstName='Kathy',LastName='Brown',Department='Technology'); //List to hold the new contacts to upsert List<Contact> contacts = new List<Contact> {josh, Kathy}; // Call upsert upsert contacts; // Result: Josh is updated and Kathy is created.

Ex: update a contact and its related account using two update statements

// Query for the contact, which has been associated with an account. Contact queriedContact = [SELECT Account.Name FROM Contact WHERE FirstName = 'Mario' AND LastName='Ruiz' LIMIT 1]; // Update the contact's phone number queriedContact.Phone = '(415)555-1213'; // Update the related account industry queriedContact.Account.Industry = 'Technology'; // Make two separate calls // 1. This call is to update the contact's phone. update queriedContact; // 2. This call is to update the related account's Industry field. update queriedContact.Account;

Ex: how to get the ID on the sObject that corresponds to the inserted account

//Create the account sObject Account acct = new Account(Name='Acme', Phone='(415)555-1212', NumberOfEmployees='100'); // Insert the account by using DML insert acct; // Get the new ID on the inserted sObject argument ID acctID = acct.ID; // Display log result (the ID will be different in your case) //DEBUG|ID = 001D000000JmKkeIAF

What is correct about a generic sObject?

A generic sObject variable can be assigned to any specific sObject, standard or custom. Such as Account or Book__c

SearchGroup Values

ALL FIELDS NAME FIELDS EMAIL FIELDS PHONE FIELDS SIDEBAR FIELDS

Ex: retrieve all account records with Name and Phone fields and return an array of Account sObjects

Account [ ] accts = [SELECT Name, Phone FROM Account];

Ex: delete the account

Account [ ] queriedAccounts = [SELECT Id FROM Account WHERE Name='SFDC Account']; delete queriedAccounts;

Cast a Generic sObject to Account

Account acct = (Account)myGenericSObject; String name = acct.Name; String phone = acct.Phone;

Create an sObject

Account acct = new Account();

Dot Notation Equivalent to Account Name, Phone numbers, and Number of Employees

Account acct = new Account(); acct.Name = 'Acme'; acct.Phone = '(415)555-1212'; acct.NumberOfEmployees = 100;

Create a New Account sObject and Populate its Name field with a string value

Account acct = new Account(Name='Acme'); To add phone number and number of employees: Account acct = new Account(Name='Acme', Phone='(415)555-1212', NumberOfEmployees=100);

Ex: add a contact to an account (related record) by setting the AccountId field on the contact

Account acct = new Account(Name='SFDC Account'); insert acct; // Once the account is inserted, the sObject will be // populated with an ID. // Get this ID. ID acctID = acct.ID; // Add a contact to this account. Contact mario = new Contact( FirstName='Mario', LastName='Ruiz', Phone='415.555.1212', AccountId=acctID); insert mario;

Ex: retrieve first account returned

Account oneAccountOnly = [SELECT Name,Phone FROM Account LIMIT 1];

Ex: use the Email field on Contact because it has idLookup property set -insert Jame Smith contact, create a second Contact sObject, populate it with the same email, call upsert to update the contact by using the email field for matching

Contact jane = new Contact(FirstName='Jane',LastName='Smith',Email='[email protected]',Description='Contact of the day'); insert jane; // 1. Upsert using an idLookup field // Create a second sObject variable. // This variable doesn't have any ID set. Contact jane2 = new Contact(FirstName='Jane',LastName='Smith',Email='[email protected]',Description='Prefers to be contacted by email.'); //Upsert the contact by using the idLookup field for matching. upsert jane2 Contact.fields.Email; // Verify that the contact has been updated System.assertEquals('Prefers to be contacted by email.', [SELECT Description FROM Contact WHERE Id=:jane.Id].Description);

Ex: delete all contacts whose last name is Smith

Contact[ ] contactsDel = [SELECT Id FROM Contact WHERE LastName='Smith']; delete contactsDel;

Upsert

Creates new records and updates sObject records within a single statement, using a specified field to determine the presence of existing objects or the ID field if no field is specified Helps avoid creation of duplicate records and can save time since you don't have to determine which record exist first

Ex: insert and update operations each return an array of Database.SaveResult objects

Database.SaveResult[ ] results = Database.insert(recordList, false);

Call the insert method with the allOrNone set to false

Database.insert(recordList, false);

How to Create an sObject Variable

Declare a variable and assign it to an sObject instance Account acct = new Account(Name='Acme')

You can obtain an instance of an sObject, such as an Account, in what way?

Either by creating the sObject or by retrieving a persistent record from Salesforce using SOQL

Describe the relationship between sObjects and Salesforce records

Every record in Salesforce is natively represented as an sObject in Apex

Syntax for Basic SOSL Syntax

FIDN 'SearchQuery' [IN SearchGroup] [TRETURNING ObjectsAndFields]

Lists

Hold an ordered collection of objects Synonymous with arrays

DML Statements

Insert Update Upsert Delete Undelete Merge

Primitive Data Type

Integer, Double, Long, Date, Datetime, String, ID, Boolean etc.

Why is performing bulk DML operations recommended?

It helps avoid hitting governor limits, such as the DML limit of 150 statements per Apex transaction

Ex: a SOSL query searches for accounts and contacts that have any fields with the word SFDC

List<List<SObject>> searchList = [FIND 'SFDC' IN ALL FIELDS ____RETURNING Account(Name), Contact(FirstName, LastName)];

List Syntax for Declaring Color Variable

List<String> colors = new List<String>();

Merge

Merges up to three records of the same sObject type into one of the records, deleting the others, an re-parenting any related records

Assign Generic sObject Variable to any Salesforce Object

sObject sobj1 = new Account(Name='Trailhead')'; sObject sobj2 = new Book__c(Name='Workbook 1');

Ex: produce DmlException because it attempts to insert an account without the required Name field

try [ __// This causes an exception because __// the required Name field is not provided. __Account acct = new Account( ); __// Insert the account __insert acct; } catch (DmlException e) { __System.debug('A DML exception has occurred: ' + e.getMessage());

Which statements are particular to Salesforce?

upsert and merge

Ex: specify the MyExternalID field

upsert sObjectList Account.Fields.MyExternalId;


Kaugnay na mga set ng pag-aaral

Human Geography: Exam One Review

View Set

Medication Calculations NCLEX Questions

View Set

Chapter 8 - Jesus, the Promised Messiah

View Set

Top 52 C# Interview Questions and Answers

View Set

Project Management Software Exam 2

View Set

Missed questions on Guarantee Exam

View Set

Virology Test 2: Short Answer and some multiple choice

View Set

Series 65 Unit 21 Exam Questions

View Set

weathering and erosion,soil, and mass movements.

View Set