Wednesday, 29 August 2012

What is an sObject? - Apex

An sObject is any object that can be stored in the Force.com platform database. These are not objects in the sense of instances of Apex classes; rather, they are representations of data that has or will be persisted.
These persisted objects can be treated as first class citizens within the Apex language, which makes the database integration particularly intuitive and easy to use.
sObject is a generic abstract type that corresponds to any persisted object type. The generic sObject can be cast into a specific sObject type, such as an account or the Invoice_Statement__c custom object.
This creates an invoice statement, which corresponds to the Invoice_Statement__c custom object, without setting any fields and assigns the new invoice statement to an sObject.
sObject s = new Invoice_Statement__c();
The second example creates an invoice statement with some initial values for the Description__c and Status__c fields and assigns it to a variable of type Invoice_Statement__c, which is an sObject type also.
Invoice_Statement__c inv = new Invoice_Statement__c(Description__c='Test Invoice', Status__c='Pending');
This example shows how to cast an sObject variable to another sObject type. It casts the mySObjectVar variable to the Invoice_Statement__c sObject type.
Invoice_Statement__c inv = (Invoice_Statement__c)mySObjectVar;
Before inserting a new sObject record, you must set all required fields for a successful insertion. You’ll learn in Lesson 5: Apex Data Manipulation Language how to insert new records, among other things, using the Data Manipulation Language (DML).
The fields of an sObject can be set either by passing them as arguments in the constructor or after creating the sObject type by using the dot notation. This example shows how to use the dot notation to set the invoice statement’s Description__c field to a string value.
inv.Description__c = 'Test Invoice';
You can also use the dot notation to read field values.
ID id = inv.Id;
String x = inv.Name;
Now try creating an sObject, and setting and reading its fields. Execute the following:
Invoice_Statement__c inv = new Invoice_Statement__c();
inv.Description__c = 'Large invoice';
System.debug('Invoice Description: ' + inv.Description__c);
The output of the previous snippet is Invoice Description: Large invoice.

No comments:

Post a Comment