Beat the Heat with Cool Discounts

Grab Up to 20% Off on Self-Paced Courses!

Explore Now
3

sObjects in Salesforce

What is sObjects in Salesforce?

 In  Salesforce sObjects represent a record. Unlike other programming languages like Java or C#, Apex is tightly integrated with the database. Hence, we do not have to create a database connection to access the records or insert new records. Instead, in Apex, we have sObjects.

sObjects Types in Salesforce

There are two main types of sObjects: Standard sObjects and Custom sObjects.

Standard sObjects

Salesforce provides preconfigured objects known as Standard sObjects. These constitute the fundamental business entities shared by the majority of enterprises, and they form the basis of the Salesforce platform. As examples, consider:

  • Account: Stands in for a business, corporation, or other entity in a business arrangement. For instance, a rival company or business partner.
  • Contact: This acts on behalf of people, such as leads, clients, partners, or staff members connected to a particular account.
  • Lead: A ‘Lead’ indicates a possible client, someone with whom there may be future commercial contacts.
  • Opportunity: Denotes a possible sale or business transaction.

Custom sObjects

When the regular sObjects are insufficient to meet specific business demands, custom sObjects are used. Salesforce customers have the ability to construct custom sObjects—sObjects made specifically for storing data that is tailored to their needs as a business.

It’s also crucial to remember that custom sObjects can be related to both other custom sObjects and regular sObjects. This makes it possible to build intricate data models that efficiently map your particular business operations.

Declaring sObject

For example, An account record named ‘Disney’ in Apex will be referred to using an sObject, like this:

Account acc = new Account(Name=’Disney’);

The API object Name becomes the data type of the sObject variable in Apex.

Here,

  • Account: sObject data type
  • acc: sObject variable
  • new: Keyword to create new sObject Instance
  • Account(): Constructor which creates an sObject instance
  • Name =‘Disney’: Initializes the value of the Name field in account sObject

Similarly, if we want to create a contact record using Apex then we first need to create a sObject for it in Apex, like this:

Contact con = new Contact();

Defining sObject : 

There are 2 ways to assign field values to the contact sObject:

1. Through Constructor

Contact con = new Contact(firstName = ‘Shrey’, lastName = ‘Sharma’);

Similarly, for Custom Objects:

Student__c st = new Student__c(Name = ‘Arnold’);

2. Using Dot Notation

Contact con = new Contact();
con.firstName = ‘Shrey’;
con.lastName = ‘Sharma’;

If we want to assign the field values for custom fields, then also we have to write down their field API name, like:

For Standard Object:

Account acc = new Account(Name = ‘Disney’, NumberOfLocations__c = 56);

For Custom Object:

Student__c st = new Student__c(Name = ‘Arnold’, Email__c = ‘arnold @gmail.com’);

Salesforce sObject Methods

The following are methods for SObject. All are instance methods.

S.No Function Example
1 addError(errorMsg) Marks a trigger record with a custom error message and prevents any DML operation from occurring. Account acc = new Account(Name='Test Account');
acc.addError('This is a custom error message.');
2 addError(errorMsg, escape) Marks a trigger record with a custom error message, specifies if the error message should be escaped, and prevents any DML operation from occurring. Account acc = new Account(Name='Test Account');
acc.addError('This is a custom error message.', false); // Message not HTML-escaped
3 addError(exceptionError) Marks a trigger record with a custom error message and prevents any DML operation from occurring. Account acc = new Account(Name='Test Account');
acc.addError(new DmlException('This is an exception error message.'));
4 addError(exceptionError, escape) Marks a trigger record with a custom exception error message, specifies whether or not the exception error message should be escaped, and prevents any DML operation from occurring. Account acc = new Account(Name='Test Account');
acc.addError(new DmlException('This is an exception error message.'), true);
5 addError(fieldName, errorMsg) Dynamically add errors to fields of an SObject associated with the specified field name. Account acc = new Account(Name='Test Account');
acc.addError('Name', 'Invalid Account Name');
6 addError(fieldToken, errorMsg) Dynamically add errors to an SObject instance associated with the specified field. Account acc = new Account(Name='Test Account');
acc.addError(Account.Name, 'Invalid Account Name');
7 addError(fieldName, errorMsg, escape) Dynamically add errors to fields of an SObject associated with the specified field name. Account acc = new Account(Name='Test Account');
acc.addError('Name', 'Invalid Account Name', false); // Error message not HTML-escaped
8 addError(fieldToken, errorMsg, escape) Dynamically add errors to an SObject instance associated with the specified field. Account acc = new Account(Name='Test Account');
acc.addError(Account.Name, 'Invalid Account Name', true); // Error message HTML-escaped
9 clear() Clears all field values Account acc = new Account(Name='Test Account', Industry='Technology');
acc.clear();
System.debug(acc); // Outputs: Account:{}
10 clone(preserveId, isDeepClone, preserveReadonlyTimestamps, preserveAutonumber) Creates a copy of the SObject record. Account acc = new Account(Name='Test Account');
Account accClone = acc.clone(false, true, true, true);
System.debug(accClone); // Outputs a cloned Account record
11 get(fieldName) Returns the value for the field specified by fieldName, such as AccountNumber. Account acc = new Account(Name='Test Account');
String name = (String)acc.get('Name');
System.debug(name); // Outputs: Test Account
12 get(field) Returns the value for the field specified by the field token Schema.sObjectField, such as Schema.Account.AccountNumber. Account acc = new Account(Name='Test Account');
String name = (String)acc.get(Account.Name);
System.debug(name); // Outputs: Test Account
13 getCloneSourceId() Returns the ID of the entity from which an object was cloned. Account acc = new Account(Name='Original Account');
Account accClone = acc.clone(false);
Id cloneSourceId = accClone.getCloneSourceId();
System.debug(cloneSourceId); // Outputs: Original Account's ID
14 getErrors() Returns a list of Database.Error objects for an SObject instance. Account acc = new Account();
acc.addError('Sample Error');
List errors = acc.getErrors();
System.debug(errors); // Outputs: List of errors on the Account
15 getOptions() Returns the database.DMLOptions object for the SObject. Account acc = new Account();
Database.DMLOptions dmlOptions = acc.getOptions();
System.debug(dmlOptions); // Outputs the DMLOptions for the Account
16 getPopulatedFieldsAsMap() Returns a map of populated field names and their corresponding values. Account acc = new Account(Name='Test Account', Industry='Technology');
Map fieldMap = acc.getPopulatedFieldsAsMap();
System.debug(fieldMap); // Outputs: {Name=Test Account, Industry=Technology}
17 getSObject(fieldName) Returns the value for the specified field. Used primarily with dynamic DML to access external IDs. Account acc = [SELECT Id, (SELECT Id FROM Contacts) FROM Account WHERE Name='Test Account' LIMIT 1];
SObject contactList = acc.getSObject('Contacts');
System.debug(contactList); // Outputs: List of contacts related to the Account
18 getSObject(field) Returns the value for the field specified by the field token Schema.sObjectField. Account acc = [SELECT Id, (SELECT Id FROM Contacts) FROM Account WHERE Name='Test Account' LIMIT 1];
SObject contactList = acc.getSObject(Account.Contacts);
System.debug(contactList); // Outputs: List of contacts related to the Account
19 getSObjects(fieldName) Returns the values for the specified field. Primarily used with dynamic DML to access child relationships. Account acc = [SELECT Id, (SELECT Id FROM Contacts) FROM Account WHERE Name='Test Account' LIMIT 1];
List contacts = acc.getSObjects('Contacts');
System.debug(contacts); // Outputs: List of contacts related to the Account
20 getSObjects(field) Returns the value for the field specified by the field token Schema.fieldName. Account acc = [SELECT Id, (SELECT Id FROM Contacts) FROM Account WHERE Name='Test Account' LIMIT 1];
List contacts = acc.getSObjects(Account.Contacts);
System.debug(contacts); // Outputs: List of contacts related to the Account
21 getSObjectType() Returns the token for this SObject. Account acc = new Account();
Schema.SObjectType objType = acc.getSObjectType();
System.debug(objType); // Outputs: Account
22 getQuickActionName() Retrieves the name of a quick action associated with this SObject. Account acc = new Account();
String actionName = acc.getQuickActionName();
System.debug(actionName); // Outputs the quick action name
23 hasErrors() Returns true if an SObject instance has associated errors. Account acc = new Account();
acc.addError('Sample Error');
Boolean hasErrors = acc.hasErrors();
System.debug(hasErrors); // Outputs: true
24 isClone() Returns true if an entity is cloned from something. Account acc = new Account(Name='Test Account');
Account acc2 = acc.clone();
System.debug(acc2.isClone()); // Outputs: true
25 isSet(fieldName) Returns true if the sObject field is populated, either by direct assignment or by inclusion in a SOQL query. Account acc = new Account(Name='Test Account');
System.assertEquals(true, acc.isSet('Name'));
26 isSet(field) Returns true if the sObject field is populated, either by direct assignment or by inclusion in a SOQL query. Account acc = new Account(Name='Test Account');
System.assertEquals(true, acc.isSet(Account.Name));
27 put(fieldName, value) Sets the value for the specified field and returns the previous value for the field. Account acc = new Account(Name='Test Account');
acc.put('Name', 'Test Account2');
System.debug(acc);
28 put(field, value) Sets the value for the field specified by the field token Schema.sObjectField. Account acc = new Account(Name='Test Account');
acc.put(Schema.Account.Name, 'Test Account2');
System.debug(acc);
29 putSObject(fieldName, value) Sets the value for the specified field. Primarily used with dynamic DML for setting external IDs. Account acc = new Account(name='Acme', description='Acme Account');
insert acc;
Contact con = new Contact(lastname='AcmeCon', accountId=acc.id);
insert con;
Contact contactDB = [SELECT Id, AccountId, Account.Name FROM Contact WHERE id = :con.id LIMIT 1];
contactDB.putSObject('Account', new Account(name='Not Acme'));
30 putSObject(fieldToken, value) Sets the value for the field specified by the token Schema.SObjectType. Account acc = new Account(Name='Test Account');
Contact con = new Contact(lastname='NewContact', accountid=acc.Id);
insert con;
Contact contactDB = [SELECT Id, AccountId FROM Contact WHERE Id = :con.Id];
contactDB.putSObject(Contact.AccountId, new Account(Name='New Account'));
Salesforce Developer
Next Topic

Need more support?

Get a head start with our FREE study notes!

Learn more and get all the answers you need at zero cost. Improve your skills using our detailed notes prepared by industry experts to help you excel.

Book Free15-Minutes Career Counselling