Experience Salesforce

sObjects in Salesforce

What You’ll Learn

  • sObjects Types in Salesforce
  • Salesforce sObject Methods

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.NoFunctionExample
1addError(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.’);
2addError(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); // The message will not be HTML-escaped.
3addError(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.’));
4addError(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); // The message will be HTML-escaped.
5addError(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’);
6addError(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’);
7addError(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
8addError(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
9clear()Clears all field valuesAccount acc = new Account(Name=’Test Account’, Industry=’Technology’);acc.clear();System.debug(acc); // Outputs: Account:{}
10clone(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
11get(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
12get(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
13getCloneSourceId()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
14getErrors()Returns a list of Database.Error objects for an SObject instance. If the SObject has no errors, an empty list is returned.Account acc = new Account();acc.addError(‘Sample Error’);List<Database.Error> errors = acc.getErrors();System.debug(errors); // Outputs: List of errors on the Account
15getOptions()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
16getPopulatedFieldsAsMap()Returns a map of populated field names and their corresponding values. The map contains only the fields that have been populated in memory for the SObject instance.Account acc = new Account(Name=’Test Account’, Industry=’Technology’);Map<String, Object> fieldMap = acc.getPopulatedFieldsAsMap();System.debug(fieldMap); // Outputs: {Name=Test Account, Industry=Technology}
17getSObject(fieldName)Returns the value for the specified field. This method is primarily used with dynamic DML to access values for 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
18getSObject(field)Returns the value for the field specified by the field token Schema.sObjectField, such as, Schema.MyObj.MyExternalId. This method is primarily used with dynamic DML to access values for external IDs.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
19getSObjects(fieldName)Returns the values for the specified field. This method is primarily used with dynamic DML to access values for associated objects, such as child relationships.Account acc = [SELECT Id, (SELECT Id FROM Contacts) FROM Account WHERE Name=’Test Account’ LIMIT 1];List<SObject> contacts = acc.getSObjects(‘Contacts’);System.debug(contacts); // Outputs: List of contacts related to the Account
20getSObjects(field)Returns the value for the field specified by the field token Schema.fieldName, such as, Schema.Account.Contact. This method is primarily used with dynamic DML to access values for associated objects, such as child relationships.Account acc = [SELECT Id, (SELECT Id FROM Contacts) FROM Account WHERE Name=’Test Account’ LIMIT 1];List<SObject> contacts = acc.getSObjects(Account.Contacts);System.debug(contacts); // Outputs: List of contacts related to the Account
21getSObjectType()Returns the token for this SObject. This method is primarily used with describe information.Account acc = new Account();Schema.SObjectType objType = acc.getSObjectType();System.debug(objType); // Outputs: Account
22getQuickActionName()Retrieves the name of a quick action associated with this SObject. Typically used in triggers.Account acc = new Account();String actionName = acc.getQuickActionName();System.debug(actionName); // Outputs the quick action name
23hasErrors()Returns true if an SObject instance has associated errors. The error message can be associated to the SObject instance by using SObject.addError(), validation rules, or by other means.Account acc = new Account();acc.addError(‘Sample Error’);Boolean hasErrors = acc.hasErrors();System.debug(hasErrors); // Outputs: true
24isClone()Returns true if an entity is cloned from something, even if the entity hasn’t been saved. The method can only be used within the transaction where the entity is cloned, as clone information doesn’t persist in subsequent transactions.Account acc = new Account(Name=’Test Account’);Account acc2 = acc.clone();(‘This is a custom error message.’);
25isSet(fieldName)Returns information about the queried sObject field. Returns true if the sObject field is populated, either by direct assignment or by inclusion in a SOQL query. Returns false if the sObject field isn’t set. If an invalid field is specified, an SObjectException is thrown.Account acc = new Account(Name=’Test Account’);System.assertEquals(true, accc.isSet(‘Name’));(‘This is a custom error message.’, false); // The message will not be HTML-escaped.
26isSet(field)Returns information about the queried sObject field. Returns true if the sObject field is populated, either by direct assignment or by inclusion in a SOQL query. Returns false if the sObject field isn’t set. If an invalid field is specified, an SObjectException is thrown.Account acc = new Account(Name=’Test Account’);acc.addError(new DmlException(‘This is an exception error message.’));
27put(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);(new DmlException(‘This is an exception error message.’), true); // The message will be HTML-escaped.
28put(field, value)Sets the value for the field specified by the field token Schema.sObjectField, such as, Schema.Account.AccountNumber and returns the previous value for the field.Account acc = new Account(Name=’Test Account’);acc.put(Schema.Account.Name, ‘Test Account2’);System.debug(acc);(‘Name’, ‘Invalid Account Name’);
29putSObject(fieldName, value)Sets the value for the specified field. This method is primarily used with dynamic DML for setting external IDs. The method returns the previous value of the field.Account acc = new Account(name = ‘Acme’, description = ‘Acme Account’);insert acc;Contact con = new contact(lastname = ‘AcmeCon’, accountid = acc.id);insert con;Account acc2 = new account(name = ‘Not Acme’);
Contact contactDB =(Contact)[SELECT Id, AccountId, Account.Name FROM Contact WHERE id = :con.id LIMIT 1];Account a = (Account)contactDB.putSObject(‘Account’, acc2);
30putSObject(fieldName, value)Sets the value for the field specified by the token Schema.SObjectType. This method is primarily used with dynamic DML for setting external IDs. The method returns the previous value of the field.Account acc = new Account(Name=’Test Account’);acc.addError(‘Name’, ‘Invalid Account Name’, false); // Error message not HTML-escaped
Salesforce Developer
Next Topic

Need Extra Support? Our FREE study materials have got you covered.

Our expert-prepared study materials provide the answers you need. Clear your doubts and improve your skills with detailed notes from industry professionals.

cts-img
Rakshabandhan Sale