Learner's Byte logo goes here
+
Oscar IT Solutions logo goes here

"Jahan clicks ruk jaate hain, wahan code shuru hota hai."

"Where clicks stop, code begins." Apex is how you build what configuration can't.

  • When do I need code?
  • What is a transaction?
  • Why 100 queries?
  • All or nothing?
  • Whose permissions?

Step 5, Part A: Apex and Transactions

Our method's Step 5 builds transactions that touch several sObjects at once. You will learn Apex, Salesforce's programming language: classes, collections, SOQL, DML, exceptions, governor limits and security, then build an all-or-nothing booking transaction for Kaveri Motors and a claim settlement for Suraksha.

You need
Steps 1 to 4 and 12 to 15, and Org C and Org D from the CRM track
You will build
Two Apex service classes, used again by the Lightning Web Components in Part B
Suggested time
5 live sessions of 90 minutes, plus about 12 hours of practice
AI skills used
Coding and Automation, Reasoning and Problem Solving

You are hereSteps 1-4 Requirements and configurationSteps 5-9 DevelopmentSteps 10-11 Test and deploySteps 12-15 Rollout

Hook: the half-saved booking

At Kaveri Motors, confirming a booking means five changes at once: create the order, add the car to it, activate it, move the deal to Booked, and give the delivery team a task.

One Saturday, the network dropped after step two. The order existed, with the car on it, but the deal still said Negotiation and nobody told the delivery team. The customer came to collect her car three weeks later and nobody had prepared it.

A flow can do several steps, but this needs checks, calculations and a guarantee: all five changes happen, or none do. That guarantee is a transaction, and Apex lets you control it precisely.

Byte This: In business, half-done is worse than not done. Build transactions that finish completely, or undo completely.

By the end of this workbook, you will be able to

  • Decide when a requirement needs Apex instead of clicks.
  • Set up VS Code, the Salesforce CLI and your org, and run Apex.
  • Write Apex with variables, collections, classes, methods and exceptions.
  • Query with SOQL and change data with DML, including partial success.
  • Explain transactions and governor limits, and write bulk-safe code.
  • Respect sharing and permissions with with sharing and user mode.
  • Build a multi-object, all-or-nothing transaction with savepoints.

Concept: when code, and its limits

Clicks before code

Use the simplest tool that works, as in every step so far. Choose Apex only when one of these is true:

What is a transaction?

A transaction is everything that happens from one request to its final save: a button click, a data load, a flow, a trigger. If any part fails, Salesforce undoes all of it, unless you handle the failure yourself.

Governor limits: sharing one building

Salesforce is multi-tenant: thousands of companies share the same servers, like flats sharing one housing society's water tank. So that no flat drains the tank, every transaction gets a fixed allowance. Exceed it, and Salesforce stops the transaction and rolls it back.

You can see where you stand at any moment with the Limits class, for example Limits.getQueries() and Limits.getLimitQueries().

Set up your developer tools

  1. Install Visual Studio Code, then the Salesforce Extension Pack from its Extensions panel.
  2. Install the Salesforce CLI from Salesforce's developer site. In a terminal, check it with sf --version.
  3. In VS Code, open the command palette and run SFDX: Create Project. Name it kaveri-dev.
  4. Run SFDX: Authorize an Org, choose Production, log in to Org C, and give it the alias orgC. Do the same for Org D as orgD in a second project, suraksha-dev.
  5. Run SFDX: Create Apex Class and name it HelloKaveri. Write a method, then right-click and choose SFDX: Deploy This Source to Org.
  6. Create a file scripts/apex/hello.apex, write System.debug(HelloKaveri.greet('Priya'));, select it and run SFDX: Execute Anonymous Apex with Currently Selected Text. Read the debug output.
HelloKaveri.cls

Useful CLI commands

The Apex language

Apex looks like Java. It is strongly typed: every variable has a type, and the compiler checks your code before it runs.

Variables and types

Execute Anonymous

Collections: List, Set and Map

Execute Anonymous

Classes, methods and exceptions

OnRoadPriceCalculator.cls

Calling Apex from other places

LeadTools.cls: an invocable method for Flow

SOQL and DML

SOQL: reading data

Execute Anonymous

SOSL searches text across several objects at once, like the global search box: FIND 'Priya' IN ALL FIELDS RETURNING Account(Name), Lead(Name). Use SOQL when you know the object; SOSL when you're searching.

DML: changing data

Execute Anonymous

All or nothing, or partial success?

Execute Anonymous

Sharing and security in Apex

By default, Apex runs in system mode: it ignores the running user's object permissions and field-level security from Step 12. You must choose to respect them.

Respecting the user's access
Our standard in this course: declare with sharing on every class, query WITH USER_MODE, and use insert as user and similar for DML, unless there's a written reason not to.

Writing bulk-safe code

Your code will rarely handle one record. A data load, a flow or a trigger can pass it 200 at once. Code written for one record breaks at scale.

Breaks at scale

Bulk-safe

Try it: watch the limits

The bulk-safe checklist

Demo: Kaveri booking transaction

The transaction from the hook, built properly. This class is used again by the booking component in Part B.

Before you start in Org C: you need the CRM 2 setup: Orders enabled with a Booked status in the Activated category, Order fields Booking Amount, Booking Receipt Number and Colour, and Booking Receipt Number on Opportunity. Add any that are missing.

What the transaction does

BookingService.cls

Walk through the code

Run it

  1. Deploy BookingService to Org C.
  2. Find an opportunity with a car on it, in Negotiation. Copy its ID from the URL.
  3. In Execute Anonymous, run System.debug(BookingService.book('PASTE_ID', 21000, 'RCPT-1001', 'Pearl White'));
  4. Check the new Order, its product, the deal at Booked, and the task.
  5. Now run it with a booking amount of 5000. Read the error and confirm nothing was created.
  6. Finally, temporarily make the Task's Subject field required by a validation rule that always fails, run a valid booking, and confirm the order was rolled back too. Then delete the rule.

Practice: Suraksha claim settlement

Write the settlement transaction for Suraksha in Org D, from these requirements. Try it before opening the model answer.

Set up first: create a custom object Claim Payment with a Master-Detail to Case, and fields Amount (Currency), UTR (Text, External ID, Unique) and Paid Date (Date). Case needs Approved Amount from CRM 3.
Open the model answer after you've written your own
ClaimSettlementService.cls

Compare your version: did you check access, guard against nulls, use a savepoint, and give the user a clear message?

Three exercises

Exercise 1: Collections and SOQL in Execute Anonymous

  1. In Org C, write a script that builds a Map<String, Integer> of open deals per stage using one SOQL query and a loop, and prints it.
  2. Rewrite it with an aggregate query, GROUP BY StageName. Which is better, and why?
  3. Find every customer who owns more than one car, using an aggregate query on Asset grouped by AccountId with HAVING COUNT(Id) > 1.
  4. Print Limits.getQueries() at the end of each script.

Exercise 2: Prove the booking transaction is all-or-nothing

Run the Demo's six "Run it" steps, and record each result in your Code Pack. Then answer: what would happen without the savepoint, if the task insert failed?

Exercise 3: Find the problem

Each snippet compiles, but will cause trouble. Choose the main problem.

Build your Code Pack

Record each class and method, what it does, the limits it uses, and how you tested it. Your work saves in this browser on this device.

Build with AI

AI coding tools, such as Agentforce Vibes in your Developer Edition org or Claude Code connected through the Salesforce DX MCP Server, can write Apex quickly. A developer who can't read and judge that code can't be trusted with it.

Three rules: Write it yourself first, then compare with AI. Check every AI class against the bulk-safe checklist and our security standard. Never deploy AI code you can't explain line by line.

Reflect and exit check

Quick test

Exit check: are you ready for Part B?

What Part B needs from you: BookingService is now an @AuraEnabled method. In Part B, a Lightning Web Component calls it from a button on the opportunity page.

Interview preparation

Apex questions are the core of developer interviews. Practise these aloud, then use our AI interview agents for feedback.

For your resume and portfolio

Training project: Built bulk-safe Apex service classes for a simulated dealership and insurer, implementing multi-object, all-or-nothing transactions with savepoints, user-mode security, custom exceptions, and methods exposed to Lightning Web Components and Flow.

Trainer notes

Open the suggested session plan and coaching notes
SessionCoverStudents leave with
1 (90 min)Hook, when code, transactions and limits. Set up VS Code and the CLI together.HelloKaveri deployed and run
2 (90 min)The language: types, collections, classes, exceptions. Live coding the calculator.Calculator working
3 (90 min)SOQL, DML, partial success, security. Exercise 1.Exercise 1 done
4 (90 min)Bulk-safe code and the limits simulator. BookingService live, line by line.Exercise 2 done
5 (90 min)Suraksha practice, Exercise 3, code reviews in pairs.Code Pack, reflection and exit check

Common mistakes to catch

  • Queries or DML inside loops. Run the 200-record test every time.
  • Using Double for money. Use Decimal.
  • Single-record query assignment, Account a = [SELECT ...], which throws when nothing is found. Query into a list and check it.
  • Catching exceptions and doing nothing, so failures vanish silently.
  • Leaving out the sharing keyword, or querying without user mode.
  • Hard-coded IDs, which differ between orgs.

Check before each batch

Install the current CLI and extensions on a clean machine and walk through setup; menu names change. Note that tests are taught fully in Step 10, but students should already run their code in Execute Anonymous.