Hello everyone, welcome to sfdcAmplified. Today we will understand sObjects in Apex.
Topics to be covered
- What is an sObject
- How to create sObject Variables
- How to access sobject Fields
What is an sObject ?
sObject are nothing but salesforce objects i.e. both custom and standard object in Salesforce are called sobject.
For Example: Account, Contact, Opportunity are standard object. Hotel__c is custom object which we create in Salesforce for the customized need of business.
How to create sObject variable in apex?
Standard Object
Account acc = new Account();
Explanation
Here Account is the data type and acc is the variable.
We must use the new keyword in order to instantiate an object. Also note that acc variable is initialized to null. You can see that in the below image.
Output
Custom Object
Hotel__c h = new Hotel__c();
Explanation
Here “__c” represents custom object created by us. By using this “__c” we can differentiate between standard object and custom object.
There are two ways to populate records in fields in Apex.
1. Add fields inside the constructor.
Account acc = new Account(Name='Smriti', Type ='Customer ' ); insert acc;
Output
2. Use the dot notation to add fields to an sObject.
Example 1
Account acc = new Account(); acc.Name = 'Sfdc Amplified'; acc.Type = 'Customer'; insert acc; system.debug(acc);
Output
Example 2
Hotel__c h = new Hotel__c(); h.name = 'marriott'; insert h; system.debug(h);
Output
Like you can see above, SObject fields can be accessed with simple dot notation. So I am able to access Name field with simple dot notation.
Note: We need to populate the required field before inserting the record or otherwise record wont be inserted.
So suppose SLA, SLA Expiration Date and SLA Serial Number are required fields on account object then you need to populate those fields to insert the account record
Account acc = new Account(); acc.Name = 'Sfdc Amplified'; acc.Type = 'Customer'; acc.Active__c = 'Yes'; acc.SLA__c = 'Gold'; acc.SLAExpirationDate__c = date.parse('9/11/2019'); acc.SLASerialNumber__c = '123'; insert acc; system.debug(acc);
Associate one field value inside another object.
Account a = new Account (name = 'Suman'); insert a; system.debug('account'+ a); Contact c = new Contact (LastName = 'Sharan'); c.AccountId = a.id; insert c; system.debug('contact'+ c);
Now to associate a contact with the account we use the ID field of the account. The above code shows how an account and a contact can be associated with one another.
Output
Exercise
Create an Account record in Apex with name = ‘Test’
I hope you enjoyed this article. For more of these articles stay tuned!
Get latest updates
If you like the Video then subscribe to Youtube Channel
If you like the Article then subscribe to the Blog
Together we can learn faster
You can join the Whatsapp group
You can join Facebook group
You can join Twitter
You can join Instagram
Reference