Apex Flashcards
Apex is
Hosted—Apex is saved, compiled, and executed on the server—the Lightning Platform.
Object oriented—Apex supports classes, interfaces, and inheritance.
Strongly typed—Apex validates references to objects at compile time.
Multitenant aware—Because Apex runs in a multitenant platform, it guards closely against runaway code by enforcing limits, which prevent code from monopolizing shared resources.
Integrated with the database—It is straightforward to access and manipulate records. Apex provides direct access to records and their fields, and provides statements and query languages to manipulate those records.
Data focused—Apex provides transactional access to the database, allowing you to roll back operations.
Easy to use—Apex is based on familiar Java idioms.
Easy to test—Apex provides built-in support for unit test creation, execution, and code coverage. Salesforce ensures that all custom Apex code works as expected by executing all unit tests prior to any platform upgrades.
Versioned—Custom Apex code can be saved against different versions of the API.
Unlike other object-oriented programming languages, Apex supports
Unlike other object-oriented programming languages, Apex supports:
- Cloud development as Apex is stored, compiled, and executed in the cloud.
- Triggers, which are similar to triggers in database systems.
- Database statements that allow you to make direct database calls and query languages to query and search data.
- Transactions and rollbacks.
- The global access modifier, which is more permissive than the public modifier and allows access across namespaces and applications.
- Versioning of custom code.
- In addition, Apex is a case-insensitive language.
Choose a Salesforce Org for Apex Development
You can develop Apex in a sandbox, scratch org, or Developer Edition org, but not directly in a production org. With so many choices, here’s some help to determine which org type is right for you and how to create it.
Sandboxes (Recommended)
A sandbox is a copy of your production org’s metadata in a separate environment, with varying amounts of data depending on the sandbox type. A sandbox provides a safe space for developers and admins to experiment with new features and validate changes before deploying code to production. Developer and Developer Pro sandboxes with source tracking enabled can take advantage of many of the features of our Salesforce DX source-driven development tools, including Salesforce CLI, Code Builder, and DevOps Center.
Scratch Orgs (Recommended)
A scratch org is a source-driven and temporary deployment of Salesforce code and metadata. A scratch org is fully configurable, allowing you to emulate different Salesforce editions with different features and settings. Scratch orgs have a maximum 30-day lifespan, with the default set at 7 days.
Developer Edition (DE) Orgs
A DE org is a free org that provides access to many of the features available in an Enterprise Edition org. Developer Edition orgs can become out-of-date over time and have limited storage. Developer Edition orgs don’t have source tracking enabled and can’t be used as development environments in DevOps Center. Developer Edition orgs expire if they aren’t logged into regularly. You can sign up for as many Developer Edition orgs as you like on the Developer Edition Signup page.
Trial Edition Orgs
Trial editions usually expire after 30 days, so they’re great for evaluating Salesforce functionality but aren’t intended for use as a permanent development environment. Although Apex triggers are available in trial editions, they’re disabled when you convert to any other edition. Deploy your code to another org before conversion to retain your Apex triggers. Salesforce offers several product- and industry-specific free trial orgs.
Production Orgs (Not Supported)
A production org is the final destination for your code and applications, and has live users accessing your data. You can’t develop Apex in your Salesforce production org, and we recommend that you avoid directly modifying any code or metadata directly in production. Live users accessing the system while you’re developing can destabilize your data or corrupt your application.
Developer Console
The Developer Console is an integrated development environment (IDE) built into Salesforce. Use it to create, debug, and test Apex classes and triggers.
To open the Developer Console from Lightning Experience: Click the quick access menu (Gear icon in upper right of Salesforce org), then click Developer Console.
To open the Developer Console from Salesforce Classic: Click Your Name | Developer Console.
The Developer Console supports these tasks:
- Writing code—You can add code using the source code editor. Also, you can browse packages in your organization.
- Compiling code—When you save a trigger or class, the code is automatically compiled. Any compilation errors are reported.
- Debugging—You can view debug logs and set checkpoints that aid in debugging.
- Testing—You can execute tests of specific test classes or all tests in your organization, and you can view test results. Also, you can inspect code coverage.
- Checking performance—You can inspect debug logs to locate performance bottlenecks.
- SOQL queries—You can query data in your organization and view the results using the Query Editor.
- Color coding and autocomplete—The source code editor uses a color scheme for easier readability of code elements and provides autocompletion for class and method names.
Data Types
In Apex, all variables and expressions have a data type, such as sObject, primitive, or enum.
1. A primitive, such as an Integer, Double, Long, Date, Datetime, String, ID, or Boolean (see Primitive Data Types)
2. An sObject, either as a generic sObject or as a specific sObject, such as an Account, Contact, or MyCustomObject_c (see Working with sObjects in Chapter 4.)
A collection, including:
3. A list (or array) of primitives, sObjects, user defined objects, objects created from Apex classes, or collections (see Lists)
4. A set of primitives (see Sets)
5. A map from a primitive to a primitive, sObject, or collection (see Maps)
6. A typed list of values, also known as an enum (see Enums)
7. Objects created from user-defined Apex classes (see Classes, Objects, and Interfaces)
8. Objects created from system supplied Apex classes
9. Null (for the null constant, which can be assigned to any variable)
Methods can return values of any of the listed types, or return no value and be of type Void.
Type checking is strictly enforced at compile time.
sObject Types
Account a = new Account(); MyCustomObjectc co = new MyCustomObject\_\_c(); // Cast the generic variable s from the example above // into a specific account and account variable a Account a = (Account) s; // The following generates a runtime error Contact c = (Contact) s;
Custom Labels
Custom labels aren’t standard sObjects. You can’t create a new instance of a custom label. You can only access the value of a custom label using system.label.label_name. For example:
String errorMsg = System.Label.genericerror;
The following example shows how you can use SOSL over a set of records to determine their object types. Once you have converted the generic SObject record into a Contact, Lead, or Account, you can modify its fields accordingly
public class convertToCLA { List<Contact> contacts = new List<Contact>(); List<Lead> leads = new List<Lead>(); List<Account> accounts = new List<Account>(); public void convertType(String phoneNumber) { List<List<SObject>> results = [FIND :phoneNumber IN Phone FIELDS RETURNING Contact(Id, Phone, FirstName, LastName), Lead(Id, Phone, FirstName, LastName), Account(Id, Phone, Name)]; List<SObject> records = new List<SObject>(); records.addAll(results[0]); //add Contact results to our results super-set records.addAll(results[1]); //add Lead results records.addAll(results[2]); //add Account results if (!records.isEmpty()) { for (Integer i = 0; i < records.size(); i++) { SObject record = records[i]; if (record.getSObjectType() == Contact.sObjectType) { contacts.add((Contact) record); } else if (record.getSObjectType() == Lead.sObjectType){ leads.add((Lead) record); } else if (record.getSObjectType() == Account.sObjectType) { accounts.add((Account) record); } } } } }
Using SObject Fields
SObject fields can be initially set or not set (unset); unset fields are not the same as null or blank fields. When you perform a DML operation on an SObject, you can change a field that is set; you can’t change unset fields.
Note
To erase the current value of a field, set the field to null.
If an Apex method takes an SObject parameter, you can use the System.isSet() method to identify the set fields. If you want to unset any fields to retain their values, first create an SObject instance. Then apply only the fields you want to be part of the DML operation.
An expression with SObject fields of type Boolean evaluates to true only if the SObject field is true. If the field is false or null, the expression evaluates to false.
This example code shows an expression that checks if the IsActive field of a Campaign object is null. Because this expression always evaluates to false, the code in the if statement is never executed.
Campaign cObj= new Campaign(); ... if (cObj.IsActive == null) { ... // IsActive is evaluated to false and this code block is not executed. }
Single vs. Bulk DML Operations
You can perform DML operations either on a single sObject, or in bulk on a list of sObjects. Performing bulk DML operations is the recommended way because it helps avoid hitting governor limits, such as the DML limit of 150 statements per Apex transaction.
Another DML governor limit is the total number of rows that can be processed by DML operations in a single transaction, which is 10,000. All rows processed by all DML calls in the same transaction count incrementally toward this limit. For example, if you insert 100 contacts and update 50 contacts in the same transaction, your total DML processed rows are 150. You still have 9,850 rows left (10,000 - 150).
System Context and Sharing Rules
Most DML operations execute in system context, ignoring the current user’s permissions, field-level security, organization-wide defaults, position in the role hierarchy, and sharing rules.
Note
If you execute DML operations within an anonymous block, they execute using the current user’s object and field-level permissions.
DML Operations, except create
Among the operations you can perform are record updates, deletions, restoring records from the Recycle Bin, merging records, or converting leads. After querying for records, you get sObject instances that you can modify and then persist the changes of.
DML Statements vs. Database Class Methods
Apex offers two ways to perform DML operations: using DML statements or Database class methods. This provides flexibility in how you perform data operations. DML statements are more straightforward to use and result in exceptions that you can handle in your code.
One difference between the two options is that by using the Database class method, you can specify whether or not to allow for partial record processing if errors are encountered. You can do so by passing an additional second Boolean parameter. If you specify false for this parameter and if a record fails, the remainder of DML operations can still succeed. Also, instead of exceptions, a result object array (or one result object if only one sObject was passed in) is returned containing the status of each operation and any errors encountered. By default, this optional parameter is true, which means that if at least one sObject can’t be processed, all remaining sObjects won’t and an exception will be thrown for the record that causes a failure.
The following helps you decide when you want to use DML statements or Database class methods.
Use DML statements if you want any error that occurs during bulk DML processing to be thrown as an Apex exception that immediately interrupts control flow (by using try. . .catch blocks). This behavior is similar to the way exceptions are handled in most database procedural languages.
Use Database class methods if you want to allow partial success of a bulk DML operation—if a record fails, the remainder of the DML operation can still succeed. Your application can then inspect the rejected records and possibly retry the operation. When using this form, you can write code that never throws DML exception errors. Instead, your code can use the appropriate results array to judge success or failure. Note that Database methods also include a syntax that supports thrown exceptions, similar to DML statements.
Most operations overlap between the two, except for a few.
The convertLead operation is only available as a Database class method, not as a DML statement.
The Database class also provides methods not available as DML statements, such as methods transaction control and rollback, emptying the Recycle Bin, and methods related to SOQL queries.
DML Operations As Atomic Transactions
DML operations execute within a transaction. All DML operations in a transaction either complete successfully, or if an error occurs in one operation, the entire transaction is rolled back and no data is committed to the database. The boundary of a transaction can be a trigger, a class method, an anonymous block of code, an Apex page, or a custom Web service method.
All operations that occur inside the transaction boundary represent a single unit of operations. This also applies to calls that are made from the transaction boundary to external code, such as classes or triggers that get fired as a result of the code running in the transaction boundary. For example, consider the following chain of operations: a custom Apex Web service method calls a method in a class that performs some DML operations. In this case, all changes are committed to the database only after all operations in the transaction finish executing and don’t cause any errors. If an error occurs in any of the intermediate steps, all database changes are rolled back and the transaction isn’t committed.
DML: Inserting and Updating Records
Account[] accts = new List<Account>(); for(Integer i=0;i<3;i++) { Account a = new Account(Name='Acme' + i, BillingCity='San Francisco'); accts.add(a); } Account accountToUpdate; try { insert accts; // Update account Acme2. accountToUpdate = [SELECT BillingCity FROM Account WHERE Name='Acme2' AND BillingCity='San Francisco' LIMIT 1]; // Update the billing city. accountToUpdate.BillingCity = 'New York'; // Make the update call. update accountToUpdate; } catch(DmlException e) { System.debug('An unexpected error has occurred: ' + e.getMessage()); } // Verify that the billing city was updated to New York. Account afterUpdate = [SELECT BillingCity FROM Account WHERE Id=:accountToUpdate.Id]; System.assertEquals('New York', afterUpdate.BillingCity);
DML: Inserting Related Records
You can insert records related to existing records if a relationship has already been defined between the two objects, such as a lookup or master-detail relationship. A record is associated with a related record through a foreign key ID. For example, when inserting a new contact, you can specify the contact’s related account record by setting the value of the AccountId field.
try { 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 con = new Contact( FirstName='Joe', LastName='Smith', Phone='415.555.1212', AccountId=acctID); insert con; } catch(DmlException e) { System.debug('An unexpected error has occurred: ' + e.getMessage()); }
DML: Updating Related Records
Fields on related records can’t be updated with the same call to the DML operation and require a separate DML call. For example, if inserting a new contact, you can specify the contact’s related account record by setting the value of the AccountId field. However, you can’t change the account’s name without updating the account itself with a separate DML call. Similarly, when updating a contact, if you also want to update the contact’s related account, you must make two DML calls. The following example updates a contact and its related account using two update statements.
DML: Relating Records by Using an External ID
Add related records by using a custom external ID field on the parent record. Associating records through the external ID field is an alternative to using the record ID. You can add a related record to another record only if a relationship (such as master-detail or lookup) has been defined for the objects involved.
This example relates a new opportunity to an existing account. The Account sObject has a custom field marked as External ID. An opportunity record is associated to the account record through the custom External ID field. The example assumes that:
The Account sObject has an external ID field of type text and named MyExtID
An account record exists where MyExtID_c = ‘SAP111111’
Before the new opportunity is inserted, the account record is added to this opportunity as an sObject through the Opportunity.Account relationship field.
Opportunity newOpportunity = new Opportunity( Name='OpportunityWithAccountInsert', StageName='Prospecting', CloseDate=Date.today().addDays(7)); // Create the parent record reference. // An account with external ID = 'SAP111111' already exists. // This sObject is used only for foreign key reference // and doesn't contain any other fields. Account accountReference = new Account( MyExtID\_\_c='SAP111111'); // Add the account sObject to the opportunity. newOpportunity.Account = accountReference; // Create the opportunity. Database.SaveResult results = Database.insert(newOpportunity);
DML: Creating Parent and Child Records in a Single Statement Using Foreign Keys
You can use external ID fields as foreign keys to create parent and child records of different sObject types in a single step instead of creating the parent record first, querying its ID, and then creating the child record. To do this:
Create the child sObject and populate its required fields, and optionally other fields.
Create the parent reference sObject used only for setting the parent foreign key reference on the child sObject. This sObject has only the external ID field defined and no other fields set.
Set the foreign key field of the child sObject to the parent reference sObject you just created.
Create another parent sObject to be passed to the insert statement. This sObject must have the required fields (and optionally other fields) set in addition to the external ID field.
Call insert by passing it an array of sObjects to create. The parent sObject must precede the child sObject in the array, that is, the array index of the parent must be lower than the child’s index.
You can create related records that are up to 10 levels deep. Also, the related records created in a single call must have different sObject types. For more information, see Creating Records for Different Object Types in the SOAP API Developer Guide.
The following example shows how to create an opportunity with a parent account using the same insert statement. The example creates an Opportunity sObject and populates some of its fields, then creates two Account objects. The first account is only for the foreign key relationship, and the second is for the account creation and has the account fields set. Both accounts have the external ID field, MyExtID_c, set. Next, the sample calls Database.insert by passing it an array of sObjects. The first element in the array is the parent sObject and the second is the opportunity sObject. The Database.insert statement creates the opportunity with its parent account in a single step. Finally, the sample checks the results and writes the IDs of the created records to the debug log, or the first error if record creation fails. This sample requires an external ID text field on Account called MyExtID.
public class ParentChildSample { public static void InsertParentChild() { Date dt = Date.today(); dt = dt.addDays(7); Opportunity newOpportunity = new Opportunity( Name='OpportunityWithAccountInsert', StageName='Prospecting', CloseDate=dt); // Create the parent reference. // Used only for foreign key reference // and doesn't contain any other fields. Account accountReference = new Account( MyExtID\_\_c='SAP111111'); newOpportunity.Account = accountReference; // Create the Account object to insert. // Same as above but has Name field. // Used for the insert. Account parentAccount = new Account( Name='Hallie', MyExtID\_\_c='SAP111111'); // Create the account and the opportunity. Database.SaveResult[] results = Database.insert(new SObject[] { parentAccount, newOpportunity }); // Check results. for (Integer i = 0; i < results.size(); i++) { if (results[i].isSuccess()) { System.debug('Successfully created ID: ' \+ results[i].getId()); } else { System.debug('Error: could not create sobject ' \+ 'for array element ' + i + '.'); System.debug(' The error reported was: ' \+ results[i].getErrors()[0].getMessage() + '\n'); } } } }
DML: Upserting Records
Using the upsert operation, you can either insert or update an existing record in one call. To determine whether a record already exists, the upsert statement or Database method uses the record’s ID as the key to match records, a custom external ID field, or a standard field with the idLookup attribute set to true.
* If the key isn’t matched, then a new object record is created.
* If the key is matched once, then the existing object record is updated.
* If the key is matched multiple times, then an error is generated and the object record is not inserted or updated.
Note
Custom field matching is case-insensitive only if the custom field has the Unique and Treat “ABC” and “abc” as duplicate values (case insensitive) attributes selected as part of the field definition. If this is the case, “ABC123” is matched with “abc123.”
Account[] acctsList = [SELECT Id, Name, BillingCity FROM Account WHERE BillingCity = 'Bombay']; for (Account a : acctsList) { a.BillingCity = 'Mumbai'; } Account newAcct = new Account(Name = 'Acme', BillingCity = 'San Francisco'); acctsList.add(newAcct); try { upsert acctsList; } catch (DmlException e) { // Process exception here }
Use of upsert with an external ID can reduce the number of DML statements in your code, and help you to avoid hitting governor limits (see Execution Governors and Limits).
This example uses upsert and an external ID field Line_Item_Id_c on the Asset object to maintain a one-to-one relationship between an asset and an opportunity line item. Before running the sample, create a custom text field on the Asset object named Line_Item_Id_c and mark it as an external ID.
Note
External ID fields used in upsert calls must be unique or the user must have the View All Data permission.
public void upsertExample() { Opportunity opp = [SELECT Id, Name, AccountId, (SELECT Id, PricebookEntry.Product2Id, PricebookEntry.Name FROM OpportunityLineItems) FROM Opportunity WHERE HasOpportunityLineItem = true LIMIT 1]; Asset[] assets = new Asset[]{}; // Create an asset for each line item on the opportunity for (OpportunityLineItem lineItem:opp.OpportunityLineItems) { //This code populates the line item Id, AccountId, and Product2Id for each asset Asset asset = new Asset(Name = lineItem.PricebookEntry.Name, LineItemIDc = lineItem.Id, AccountId = opp.AccountId, Product2Id = lineItem.PricebookEntry.Product2Id); assets.add(asset); } try { upsert assets LineItemIDc; // This line upserts the assets list with // the LineItemIdc field specified as the // Asset field that should be used for matching // the record that should be upserted. } catch (DmlException e) { System.debug(e.getMessage()); } }
DML: Merging Records
When you have duplicate lead, contact, case, or account records in the database, cleaning up your data and consolidating the records might be a good idea. You can merge up to three records of the same sObject type. The merge operation merges up to three records into one of the records, deletes the others, and reparents any related records.
Merge Considerations
When merging sObject records, consider the following rules and guidelines:
1. Only leads, contacts, cases, and accounts can be merged. See sObjects That Don’t Support DML Operations.
2. You can pass a master record and up to two additional sObject records to a single merge method.
3. Using the Apex merge operation, field values on the master record always supersede the corresponding field values on the records to be merged. To preserve a merged record field value, simply set this field value on the master sObject before performing the merge.
4. External ID fields can’t be used with merge.
For more information on merging leads, contacts and accounts, see the Salesforce online help.
Example
The following shows how to merge an existing Account record into a master account. The account to merge has a related contact, which is moved to the master account record after the merge operation. Also, after merging, the merge record is deleted and only one record remains in the database. This examples starts by creating a list of two accounts and inserts the list. Then it executes queries to get the new account records from the database, and adds a contact to the account to be merged. Next, it merges the two accounts. Finally, it verifies that the contact has been moved to the master account and the second account has been deleted.
// Insert new accounts List<Account> ls = new List<Account>{ new Account(name='Acme Inc.'), new Account(name='Acme') }; insert ls; // Queries to get the inserted accounts Account masterAcct = [SELECT Id, Name FROM Account WHERE Name = 'Acme Inc.' LIMIT 1]; Account mergeAcct = [SELECT Id, Name FROM Account WHERE Name = 'Acme' LIMIT 1]; // Add a contact to the account to be merged Contact c = new Contact(FirstName='Joe',LastName='Merged'); c.AccountId = mergeAcct.Id; insert c; try { merge masterAcct mergeAcct; } catch (DmlException e) { // Process exception System.debug('An unexpected error has occurred: ' + e.getMessage()); } // Once the account is merged with the master account, // the related contact should be moved to the master record. masterAcct = [SELECT Id, Name, (SELECT FirstName,LastName From Contacts) FROM Account WHERE Name = 'Acme Inc.' LIMIT 1]; System.assert(masterAcct.getSObjects('Contacts').size() > 0); System.assertEquals('Joe', masterAcct.getSObjects('Contacts')[0].get('FirstName')); System.assertEquals('Merged', masterAcct.getSObjects('Contacts')[0].get('LastName')); // Verify that the merge record got deleted Account[] result = [SELECT Id, Name FROM Account WHERE Id=:mergeAcct.Id]; System.assertEquals(0, result.size());
DML: Deleting Records
After you persist records in the database, you can delete those records using the delete operation. Deleted records aren’t deleted permanently from Salesforce, but they are placed in the Recycle Bin for 15 days from where they can be restored.
~~~
Account[] doomedAccts = [SELECT Id, Name FROM Account
WHERE Name = ‘DotCom’];
try {
delete doomedAccts;
} catch (DmlException e) {
// Process exception here
}
~~~
DML: Referential Integrity When Deleting and Restoring Records
The delete operation supports cascading deletions. If you delete a parent object, you delete its children automatically, as long as each child record can be deleted.
For example, if you delete a case record, Apex automatically deletes any CaseComment, CaseHistory, and CaseSolution records associated with that case. However, if a particular child record is not deletable or is currently being used, then the delete operation on the parent case record fails.
The undelete operation restores the record associations for the following types of relationships:
1. Parent accounts (as specified in the Parent Account field on an account)
1. Indirect account-contact relationships (as specified on the Related Accounts related list on a contact or the Related Contacts related list on an account)
1. Parent cases (as specified in the Parent Case field on a case)
1. Master solutions for translated solutions (as specified in the Master Solution field on a solution)
1. Managers of contacts (as specified in the Reports To field on a contact)
1. Products related to assets (as specified in the Product field on an asset)
1. Opportunities related to quotes (as specified in the Opportunity field on a quote)
1. All custom lookup relationships
1. Relationship group members on accounts and relationship groups, with some exceptions
1. Tags
1. An article’s categories, publication state, and assignments
DML: Restoring Deleted Records
After you have deleted records, the records are placed in the Recycle Bin for 15 days, after which they are permanently deleted. While the records are still in the Recycle Bin, you can restore them using the undelete operation. If you accidentally deleted some records that you want to keep, restore them from the Recycle Bin.
Account a = new Account(Name='Universal Containers'); insert(a); insert(new Contact(LastName='Carter',AccountId=a.Id)); delete a; Account[] savedAccts = [SELECT Id, Name FROM Account WHERE Name = 'Universal Containers' ALL ROWS]; undelete savedAccts;
Undelete Considerations
1. You can undelete records that were deleted as the result of a merge. However, the merge reparents the child objects, and that reparenting can’t be undone.
2. To identify deleted records, including records deleted as a result of a merge, use the ALL ROWS parameters with a SOQL query.
Database Class: Converting Leads
The convertLead DML operation converts a lead into an account and contact, as well as (optionally) an opportunity. convertLead is available only as a method on the Database class; it is not available as a DML statement.
Converting leads involves the following basic steps:
1. Your application determines the IDs of any lead(s) to be converted.
2. Optionally, your application determines the IDs of any account(s) into which to merge the lead. Your application can use SOQL to search for accounts that match the lead name.
3. Optionally, your application determines the IDs of the contact or contacts into which to merge the lead. The application can use SOQL to search for contacts that match the lead contact name.
4. Optionally, the application determines whether opportunities should be created from the leads.
5. The application uses the query (SELECT … FROM LeadStatus WHERE IsConverted=true) to obtain the leads with converted status.
6. The application calls convertLead.
7. The application iterates through the returned result or results and examines each LeadConvertResult object to determine whether conversion succeeded for each lead.
8. Optionally, when converting leads owned by a queue, the owner must be specified. This is because accounts and contacts can’t be owned by a queue. Even if you are specifying an existing account or contact, you must still specify an owner.
Example
This example shows how to use the Database.convertLead method to convert a lead. It inserts a new lead, creates a LeadConvert object, sets its status to converted, and then passes it to the Database.convertLead method. Finally, it verifies that the conversion was successful.
Lead myLead = new Lead(LastName = ‘Fry’, Company=’Fry And Sons’);
insert myLead;
Database.LeadConvert lc = new database.LeadConvert();
lc.setLeadId(myLead.id);
LeadStatus convertStatus = [SELECT Id, ApiName FROM LeadStatus WHERE IsConverted=true LIMIT 1];
lc.setConvertedStatus(convertStatus.ApiName);
Database.LeadConvertResult lcr = Database.convertLead(lc);
System.assert(lcr.isSuccess());
Convert Leads Considerations
1. Field mappings: The system automatically maps standard lead fields to standard account, contact, and opportunity fields. For custom lead fields, your Salesforce administrator can specify how they map to custom account, contact, and opportunity fields. For more information about field mappings, see Salesforce Help.
2. Merged fields: If data is merged into existing account and contact objects, only empty fields in the target object are overwritten—existing data (including IDs) are not overwritten. The only exception is if you specify setOverwriteLeadSource on the LeadConvert object to true, in which case the LeadSource field in the target contact object is overwritten with the contents of the LeadSource field in the source LeadConvert object.
3. Record types: If the organization uses record types, the default record type of the new owner is assigned to records created during lead conversion. The default record type of the user converting the lead determines the lead source values available during conversion. If the desired lead source values are not available, add the values to the default record type of the user converting the lead. For more information about record types, see Salesforce Help.
4. Picklist values: The system assigns the default picklist values for the account, contact, and opportunity when mapping any standard lead picklist fields that are blank. If your organization uses record types, blank values are replaced with the default picklist values of the new record owner.
5. Automatic feed subscriptions: When you convert a lead into a new account, contact, and opportunity, the lead owner is unsubscribed from the lead record’s Chatter feed. The lead owner, the owner of the generated records, and users that were subscribed to the lead aren’t automatically subscribed to the generated records, unless they have automatic subscriptions enabled in their Chatter feed settings. They must have automatic subscriptions enabled to see changes to the account, contact, and opportunity records in their news feed. To subscribe to records they create, users must enable the Automatically follow records that I create option in their personal settings. A user can subscribe to a record so that changes to the record display in the news feed on the user’s home page. This is a useful way to stay up-to-date with changes to records in Salesforce.
- > searchList = [FIND 'Acme' IN ALL FIELDS RETURNING Contact(id,Account.Name)]*
In addition, the sObject field key can be used with insert, update, or upsert to resolve foreign keys by external ID. For example this inserts a new contact with the AccountId equal to the account with the external_id equal to ‘12345’. If there is no such account, the insert fails.
Account refAcct = new Account(externalId_c = '12345');
Contact c = new Contact(Account = refAcct, LastName = 'Kay');
insert c;
- )
SELECT Id FROM Account WHERE Name != ''
(Since Account is a large object even though Name is indexed (primary key), this filter returns most of the records, making the query non-selective.)
SELECT Id FROM Account WHERE Name != '' AND CustomField__c = 'ValueA'
(If the count of records returned by SELECT COUNT() FROM Account WHERE CustomField__c = 'ValueA' is lower than the selectivity threshold, and CustomField__c is indexed, the query is selective.)
- > searchList = [FIND :myString1 IN ALL FIELDS
RETURNING
Account (Id, Name WHERE Name LIKE :myString2
LIMIT :myInt3),
Contact,
Opportunity,
Lead
WITH DIVISION =:myString4
LIMIT :myInt5];
```
- > myQuery = search.query(SOSL_search_string);
String searchquery='FIND\'Edge*\'IN ALL FIELDS RETURNING Account(id,name),Contact, Lead';
List
- >searchList=search.query(searchquery);
- > searchResults = **search.query(queryString,AccessLevel.USERMODE*);***
User mode operation is the recommended way to avoid sharing, CRUD and FLS violations.
){}
The execute method is called for each batch of records that you pass to it and takes these parameters.
A reference to the Database.BatchableContext object.
A list of sObjects, such as List