ApexSensei

Drills › Change records (DML)

SObject field access

Change records (DML) · Beginner · 8 min · Runs in your Salesforce Developer org · Apex Path

Scenario. A reusable mapper knows some Account fields at compile time and receives other field API names dynamically.

Set and read Account fields with dot notation and dynamic SObject methods without saving a record.

What you will learn

Use dot notation when you know the field while you write the code. Use put and get when the field's API name arrives as text at run time.

account.Name = name;
account.put('Description', note);
String text = (String) account.get('Description');

put and get also accept a field token, like Account.Description.

Gotcha. get returns Object, so cast it when you need a typed value.

The task

Set and read fields on one Account in memory, using dot notation and the dynamic put and get methods.

Examples:

  • account.Name = name;, then read account.Name → Dot name: AS Field Practice
  • put the Description, then read it with get → Dynamic description: Prepared in memory
  • fields you never set read as null → Phone unset: true and Id unset: true

Requirements:

  1. Set the Account's Name with dot notation and its Description with put.
  2. Read Description back with get and cast the result to String.
  3. Do not insert the Account. It stays in memory only.
  4. Print Dot name:, Dynamic description:, Phone unset: and Id unset: in that order.

Starter code

String name = 'AS Field Practice';
String description = 'Prepared in memory';
Account account = new Account();
String dynamicDescription;

When it passes

The Account stays in memory, both access styles return the assigned values, and untouched fields remain null.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

Insert a tagged Account ›