In addition to the constructor, you can also set a field on an sObject variable using the dot notation.
String websiteUrl = 'www.Stark.com'; Account acc = new Account(); acc.Name = 'Stark Industries'; acc.Website = websiteUrl; acc.CustomField__c = 30;
Seems pretty easy! There are a couple things to keep in mind:
The field you're setting must exist on the specific sObject and it must be writable. If you attempt to set a field that does not exist you'll encounter a compilation error:
Account acc = new Account(); acc.Nameee = 'Stark Industries'; // Variable does not exist: Nameee
If you tried setting a formula field or an unwriteable system field like LastModifiedDate
you'd receive a compilation error stating: Field is not writeable: Account.LastModifiedDate
.
Account acc = new Account(); acc.LastModifiedDate = System.now(); // uh oh!
The datatypes of the field you're setting and the value you're providing must match. On Account, Name
is a text field, so it can only be set as a String. The following code would cause a compilation error saying: Illegal assignment from Integer to String
.
Account acc = new Account(); acc.Name = 1000; // 1000 is not a String datatype
You can use the dot operator to clear field values by setting them to null
.
public void mainMethod(){ Account acc = [SELECT ParentId FROM Account LIMIT 1]; acc = clearParentAccount(acc); // acc.ParentId is now blank! } public Account clearParentAccount(Account acc){ acc.ParentId = null; return acc; }
All good? Well, almost. I have an issue with the code above. sObjects are non-primitive datatypes. When passed in methods as arguments, non-primitive datatypes have their references passed by value. For a refresher on what that means, check out Considerations for Passing Parameters.
Since we're passing a non-primitive datatype into clearParentAccount()
it doesn't explicitly require a return type:
public void mainMethod(){ Account acc = [SELECT ParentId FROM Account LIMIT 1]; clearParentAccount(acc); // acc.ParentId is now blank because of how the reference was passed in } public void clearParentAccount(Account acc){ acc.ParentId = null; }
This code will work just the same. Here, acc
is a pointer to the memory address the object is stored in. So the changes we make to acc
in the method will reflect in the original variable. We don't have to explicitly return the updated variable.