sObjects

Every standard and custom object in salesforce can be declared as a data type in Apex. The syntax is:

sObject variableName = new sObject();

To populate the fields of any sObject, we enter setup > object manager > fields and relationships and use the FieldName

Let’s make a new contact.

Contact con = new Contact();
con.firstName = 'John';

You will notice it won’t let us do this. Let’s open SF org and make a new contact and this is because last name is a required field. Let’s add those in the code.

Contact con = new Contact();
con.firstName = 'John';
con.lastName = 'Smith';

We have our variables but they’re not commited into the database yet. This is the equivalent of creating a record but not pressing save. To save this in our database, we need to use DML.

DML

DML stands for Data Manipulation Language, a programming language used for inserting, deleting or modifying data in a database. It's usually a part of a bigger programming language and DML itself is considered a sub-programming language.

  • Insert To insert a value.
  • Update To update a value.
  • Upsert To update a value, and if it doesn’t exist, insert it. (UPSERT = UPDATE + INSERT).
  • Delete To delete a value.
  • Undelete To restore a value from recycle bin.

Let’s insert a record:

Contact con = new Contact();
con.firstName = 'Ayye';
con.lastName = 'Last Name';

insert con;

Going back in our org, we now have a new contact named Ayye Last Name.

When using custom objects or fields, a __c needs to be added at the end.

Invoice__c inv = new Invoice__c();
inv.lastName__c = 'Johnson';
insert inv;

To add multiple entries, initialize an object inside the for loop, update it's values and add them an external list.

List<Contact> finalList = new List<Contact>();

for(Integer i = 0; i < 10; i ++){
    Contact con = new Contact();
    con.lastName = 'Test ' + i;
    finalList.add(con);
}

insert finalList;

We initialize the Contact variable inside the for loop because the life of a variable when made inside a for loop starts when the loop starts and ends when the loop ends. So when you make a new Contact con inside the loop, it makes a new instance of con everytime the loop is run and destroys it at the end just after it adds to the list. This is similar to making 10 cups of coffee one at a time. You get your ground coffee and water at the start and once you mix it the “original” state of ground coffee and water doesn’t exist anymore and then you start over again, running a life cycle of raw ingredients to processed ingredients.

Salesforce Object Query Language (SOQL)

SOQL or Salesforce Object Query Language in simple terms is a search engine for your org that collects specific or similar records from specified Objects. In coffee making terms, it’s searching for a specific coffee across your cabinets in the kitchen and putting them down on your counter. Let’s have a look at the syntax:

[SELECT field_name, field_name2 FROM object WHERE condition AND/OR condition];
  • [] It’s necessary to encolse an SOQL statement in square brackets
  • SELECT is the keyword that denotes what to select
  • field_name is the API / Field name (not label) of the field that we want to search in
  • FROM is the keyword that denotes where to select from
  • object is the name of the object. Object__c if it’s a custom object.
  • WHERE is the keyword that denotes what conditions to search for in the field
  • condition is what are we looking for in the field(s), separated by , or an AND or OR

Let’s say you want to get some arabica coffee from cabinet 1 and the coffee should be in beans form and must be fresh.

[SELECT arabica FROM Cabinet1 WHERE form = 'ground' AND status = 'fresh' ];

Let's run an actual search on contacts made earlier:

[SELECT ID, lastName from contact WHERE lastName = 'Test 1'];

The SOQL query returns a list of results and the data type is the object it searched in.

List<Contact> con = [SELECT ID, lastName FROM contact WHERE lastName = 'Test 1'];

Real life scenarios aren't Test 1, 2 and 3 but take actual names. To search using a template form, we make use of wildcards, these are operators that work similar to fill in the blanks. There are two wildcard operators in SOQL:

  • _ means we are searching for one character specifically.
  • % means we are searching for multiple characters.

To use wildcard operators, replace = with LIKE keyword. In coffee terms

  • COFF% would return COFFEE (Multi character search)
  • T_A would return TEA (Single character serach)

Let's search for the 10 Test contacts we made earlier:

List<Contact> con = [SELECT ID, lastName FROM contact WHERE lastName LIKE 'Test%'];

This would return all values from Test 0...Test 10. But if we are looking to exclude Test 10 from our query, we would use:

List<Contact> con = [SELECT ID, lastName FROM contact WHERE lastName LIKE 'Test _'];

This would return Test 0...Test 9

We can further run complex queries by introducing comparison operators:

List<Opportunity> oppList = [SELECT ID, value FROM opportunity WHERE (value<=100000 AND value >= 50000)];

This would return all opportunities with values ranging from 50,000 to 100,000. We can also assign nicknames (called alias) to objects in SOQL queries:

[SELECT ID, lastName FROM contact c where c.lastName = 'Test'];

This is especially handy when dealing with longer custom object names and fields, and working with related objects and fields.

We can further run more template serches by introducing variables in our SOQL queries just by adding a : before the variable name:

String searchName = 'Young';
List<Contact> con = [SELECT ID, lastName FROM contact WHERE lastName = :searchName];

Usually after the SELECT keyword we include ID in our queries even if we don't use the field. This is because our operations require those fields and it's being handled in the background automatically and I would recommend almost always include ID as a field in your SOQL queries for use in future or while working in teams.

We can also limit the number of values returned by using the LIMIT keyword followed by an Integer.

[SELECT ID, LastName FROM Contact WHERE LastName = 'Test' LIMIT 10];

This will return the first 10 values it finds.

Summary

  • sObjects can be used as a Data type to store values.
  • DML Statements are used to manipulate data into the org database.
  • SOQL is a search engine of sorts that looks for values matching criteria in specified objects.
Day 9: Database Class Methods