How to Create SObject in Salesforce Apex

I created a custom logging feature to track changes to records in any object, such as an account, contact, or custom object. The method should accept the SObject type to work with any object in Salesforce. For that, we need to declare a SObject in Salesforce Apex.

Here, I will explain what an SObject is in Salesforce Apex and why it is necessary to use it. Next, I will explain how to declare a SObject in Salesforce Apex, including its methods and their explanations.

SObject in Salesforce Apex

In  Salesforce, sObjects (Salesforce Object) represent a record. Unlike other programming languages, such as 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.

It allows for dynamic handling of records when the object type is unknown at compile time. Key methods, such as get(), set(), and getPopulatedFieldsAsMap(), enable flexible access and modification of field values.

SObject can be cast to specific object types when needed. It is commonly used in triggers, utility methods, and bulk data processing, making it essential for handling records dynamically and reusable.

Types of SObjects in Salesforce

  • Standard SObjects: Salesforce provides preconfigured objects known as Standard SObjects. These constitute the fundamental business entities shared by most enterprises and form the basis of the Salesforce platform.
  • Custom SObjects: When the regular SObjects are insufficient to meet specific business demands, custom SObjects are used. Salesforce customers can construct custom sObjects—sObjects explicitly made for storing data tailored to their business needs.

It’s also crucial to remember that custom sObjects can be related to other custom sObjects and regular sObjects. This enables the creation of intricate data models that efficiently map your business operations.

1. Declare SObject Through Constructor

Syntax to declare SObject in Salesforce Apex:

For example, we have an account record named ‘TSinto Technologies’ that we want to refer to in Apex. To do so, we need to access it, as shown below.

Account acc = new Account ( Name = ’TSinto Technologies’ );
  • Account: This is a SObject data type.
  • acc: is the variable that we declared.
  • Name: This is the API Name that we saved while creating the fields.

Similarly, if a Custom SObject is named Student, the syntax is below.

Student__c  stud= new Student__c (Student_Name__c = ’Alex Anderson’ );

Here, we need to give the suffix as a double underscore c (__c), which denotes a custom object. The same is true for fields.

2. Declare SObject Using Dot Notation

Contact con = new Contact();
con.FirstName = 'Alex Anderson';

Here, first, we declare SObject, and then, using instance and dot notation, we can assign values to the fields.

Methods Used in Salesforce SObject

Below, I explained some of the methods we use in Apex Salesforce SObject.

1. get(FieldName) method to Fetch Records From SObject

In the apex code below, I declare a List with the data type SObject and a stored account record that was modified in the last five days using the WHERE clause. Then, using a for loop, we iterate stored records and display them using an SObject instance.

Then, to fetch the record from SObject, we have the get(FieldName) method, which retrieves the value of fields. As we fetch the fields from the SObject, it returns the value in object form, which we need to convert to a string. For that, we need to convert the value to a string and then store it in the String variable.

Then, using a debug method, I displayed the fetched field values.

List<SObject> accRecords = [SELECT Id, Name, LastModifiedDate  FROM Account  WHERE LastModifiedDate >= LAST_N_DAYS:5];

for(SObject acc : accRecords) {
    String accId = (String)acc.get('Id');
    String accName = (String)acc.get('Name');
    
    System.debug(' Account ID: ' + accId + '  ' + ' Account Name: ' + accName);
}

As you execute the apex code, you can see the records that we fetched from the SObject.

How to Create SObject in Salesforce Apex

2. isSet(FieldName) method in SObject

The isSet(FieldName) is a boolean method used to display the result of the value set for the particular field.

Here, we first declare an SObject and add an account name. Then, using the isSet() method, we check whether the name has been successfully set. If yes, then it will return true; otherwise, it will be false.

Account acc = new Account (Name = 'Acme Corporation');
Boolean isNameSet = acc.isSet('Name');
System.debug('Is Name Set? ' + isNameSet);

As you execute the above SObject Apex code, you can see the true boolean value is returned.

SObject in Salesforce

3. addError(ErrorMessage)

The addError() method displays a custom error message in Salesforce Apex and prevents any DML operation from occurring. Another method, addError(fieldName, errorMsg)dynamically adds 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’);

Here, we declare the Account SObject. Using an instance of the object, we add an error message to the Name field and then the custom error message that we want to display.

4. getSObjectType() Method in SObject

The getSObjectType() method is used to retrieve the Salesforce object type of the records. This method is particularly useful when working that contain Salesforce records (sObjects), as it allows us to determine the type of sObject the variable is handling. It helps ensure that you work with the correct type of records in your Apex code.

In the Apex code below, we first declared map ID and account data types. Then, using Schema.SObjectType we retrieve the SObjectType for the object, and accMap .getSObjectType is a way to reference the metadata about the account object.

As you execute the code below, you will get the object type.

Map<Id, Account> accMap = new Map<Id, Account>();
Schema.SObjectType objectType = accMap .getSObjectType();
System.debug('The Object Type of this Map Collection is: ' +objectType);
Salesforce SObjects declaration

In this way, we can use some SObject methods in Salesforce Apex to insert or retrieve records in Salesforce standard or custom objects.

Conclusion

I hope you have got an idea about SObject in Salesforce. In that, I explained what it is and why we need to declare or use it in the Salesforce Apex code. Then I explained how to declare SObject in Salesforce Apex and its methods with an explanation. Additionally, we have observed various methods for declaring SObjects in Salesforce Apex.

You may like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.