#salesforcehowto — Public Fediverse posts
Live and recent posts from across the Fediverse tagged #salesforcehowto, aggregated by home.social.
-
SOQL Basics for Salesforce Admins
If you have spent any amount of time in the Salesforce ecosystem as an admin, you know this exact routine:
A stakeholder asks for a dataset. You build a custom report type, drag and drop fields, apply filters, and hit Export. Then, because Salesforce reports cannot easily pull data across non-related branches or cross-reference two unconnected objects, you open Excel or Google Sheets. You waste 30 minutes writing nested VLOOKUP or XLOOKUP functions, cleaning up blank rows, and dealing with #N/A errors.
What if you could bypass the Report Builder, skip Excel entirely, and extract precise, relational datasets straight from Salesforce in seconds?
Meet SOQL: The Admin Query Tool Hiding in Plain Sight
SOQL stands for Salesforce Object Query Language. It is a lightweight, declarative query syntax used to read data stored in your Salesforce database. Think of it as asking Salesforce a direct question: “Give me these specific fields, from this object, where these conditions are met.”
While SOQL is often labeled as a “developer tool,” it is actually one of the most powerful super-skills a Salesforce Administrator can learn. In this guide, we will cover the basics of SOQL, demonstrate how to construct powerful queries with sorting and grouping, and show you how to leverage Salesforce Inspector to execute queries faster than you ever thought possible.
Why SOQL Beats Standard Reports and Excel
- No Report Limits: Standard Salesforce reports cap you at 2,000 rows in the UI, and multi-block joined reports can be clunky. SOQL lets you quickly inspect thousands of records at once.
- Access “Hidden” Objects: Certain system objects, such as FieldPermissions, UserRecordAccess, ApexClass, or GroupMember, are impossible or difficult to query via standard report types. SOQL gives you direct visibility into almost every object in your org.
- Say Goodbye to VLOOKUPs: Instead of exporting Contacts to Sheet A and Accounts to Sheet B to run a VLOOKUP, SOQL allows you to reach across relationships directly in a single line of query text.
- Data Operations Ready: When you pull data via SOQL, you get precise 18-character Record IDs, making the export immediately formatted and ready for Data Loader or inline updates.
Understanding SOQL Query Structure
Every basic SOQL query relies on three core clauses: SELECT, FROM, and WHERE.
SELECT Id, Name, StageName, Amount FROM Opportunity WHERE IsClosed = FalseLet’s break this down:
- SELECT: The specific Field API Names you want to retrieve. (Tip: Always use API names, such as Custom_Field__c, not field labels).
- FROM: The API Name of the Salesforce object you are querying (e.g., Account, Contact, Custom_Object__c).
- WHERE: The filtering conditions. Only records meeting these criteria will be returned.
Essential SOQL Clauses and Operators
To make your queries more precise, you can append additional clauses:
- ORDER BY: Sorts your records in ascending (ASC) or descending (DESC) order.
- LIMIT: Restricts the maximum number of records returned (e.g., LIMIT 100).
- IN: Filters against a list of values (e.g., WHERE StageName IN (‘Closed Won’, ‘Closed Lost’)).
- LIKE: Performs wild-card searches using % (e.g., WHERE Email LIKE ‘%@gmail.com’).
Master Sorting with ORDER BY (Ascending vs. Descending)
When querying individual records, use ORDER BY with ASC (smallest to largest / A to Z) or DESC (largest to smallest / Z to A). If unspecified, SOQL defaults to ASC.
When you add multiple fields separated by a comma after ORDER BY, it creates a primary sort and a secondary sort (tie-breaker).
Example: Primary & Secondary Sorting (DESC / DESC)
Goal: Pull open Opportunities, sorted so the highest-value deals appear at the top (DESC), followed by the most recently created deals (DESC).
SELECT Id, Name, Amount, StageName, CloseDate FROM Opportunity WHERE IsClosed = False ORDER BY Amount DESC, CloseDate DESC LIMIT 50How Salesforce Evaluates Multi-Field Sorting Step-by-Step
- Primary Sort (Amount DESC): Salesforce first sorts all records by Amount from highest to lowest.
- Secondary Sort (CloseDate DESC): If two or more opportunities have the exact same Amount, Salesforce uses CloseDate to break the tie, placing the one with the most recent CloseDate higher up.
Replacing VLOOKUPs with Relationship Queries
The real magic of SOQL lies in traversing relationships. In Excel, you use VLOOKUP to match an Account ID on a Contact sheet to fetch the Account Owner’s email. In SOQL, you traverse the relationship directly using dot notation (Parent Queries) or subqueries (Child Queries).
Parent Relationship Queries (Child-to-Parent)
When querying a child object (like Contact), you can traverse “up” to the parent object (Account) using dot notation.
Excel approach: Export Contacts, Export Accounts, run =VLOOKUP(C2, Accounts!A:D, 4, FALSE).
SOQL approach:
SELECT Id, FirstName, LastName, Account.Name, Account.Owner.Email, Account.Industry FROM Contact WHERE Account.Rating = 'Hot'Notice how Account.Owner.Email reaches up three levels (Contact > Account > Owner) in a single query. No spreadsheets required.
Rule of Thumb for Custom Objects: For custom lookup fields, change the __c to an __r. For example, if you have a custom lookup Building__c on Contact, query it as Building__r.Name.
Child Relationship Queries (Parent-to-Child)
What if you want to pull a list of Accounts alongside all of their related Opportunities?
SOQL approach (Subquery):
SELECT Id, Name, AnnualRevenue, (SELECT Id, Name, Amount, StageName FROM Opportunities) FROM Account WHERE Type = 'Customer - Direct'This returns every Direct Customer Account and embeds an array of its related Opportunities right inside the record row.
Enter Salesforce Inspector: The Admin’s Best Friend
While you can run SOQL inside the native Salesforce Developer Console, Web Console or VS Code, the absolute best tool for admins is Salesforce Inspector (or its popular community extension, Salesforce Inspector Reloaded).
Salesforce Web ConsoleSalesforce Inspector is a browser extension (available for Chrome, Firefox, and Edge) that adds a subtle overlay tab to your browser when logged into Salesforce.
Why Use Salesforce Inspector for SOQL?
- Instant Access: You don’t need to open Setup or launch a heavy development environment. Just click the overlay, select Data Export, and start typing.
- Auto-Completion: As you type your SOQL query, Salesforce Inspector auto-completes object and field API names in real time, saving you from constantly checking the Object Manager.
- One-Click Export Options: Once your query executes, you can instantly copy the results as CSV, Excel, or JSON.
- Direct Record Navigation: Record IDs in the Inspector results grid are clickable links. Want to inspect a returned Account? Just click its ID to open the record directly in Salesforce.
- Inline Data Cleanup: If you find bad data in your query results, Salesforce Inspector allows you to update or delete those records right from the tool interface.
Practical SOQL Recipes for Admins
To help you get started, here are three real-world administrative tasks solved with a simple SOQL query instead of complex reports or spreadsheets:
Recipe 1: Find Active Users with No Assigned Permission Sets
Find out which active users are missing a key organizational permission set.
SELECT Id, Name, Email, Profile.Name FROM User WHERE IsActive = True AND Id NOT IN ( SELECT AssigneeId FROM PermissionSetAssignment WHERE PermissionSet.Name = 'Sales_Operations_Admin' )Recipe 2: Audit Contacts with Inconsistent Address Data
Locate contacts where the mailing country is missing, but the parent Account has a billing country populated.
SELECT Id, FirstName, LastName, MailingCountry, Account.Id, Account.Name, Account.BillingCountry FROM Contact WHERE MailingCountry = NULL AND Account.BillingCountry != NULLRecipe 3: Aggregate Pipeline Metrics with GROUP BY and ORDER BY
Want a quick summary of your pipeline grouped by lead source without building a summary report? Combine aggregate functions like SUM() and COUNT() with GROUP BY and ORDER BY.
The GROUP BY clause works like a Pivot Table in Excel. It collapses individual records into summary rows based on shared values in a specific field. When you group by LeadSource, Salesforce automatically organizes all open opportunities into distinct buckets (like “Partner Referral” or “Web”) and calculates aggregate metrics such as COUNT(Id) for total deal volume and SUM(Amount) for total pipeline value for each bucket in a single clean table.
Salesforce Inspector Reloaded SOQL Query ResultsSELECT LeadSource, COUNT(Id) TotalDeals, SUM(Amount) TotalPipeline FROM Opportunity WHERE IsClosed = False GROUP BY LeadSource ORDER BY SUM(Amount) DESCBecome a More Efficient Salesforce Admin with SOQL
Learning SOQL is about becoming a dramatically more efficient Administrator. Once you get comfortable writing basic SELECT … FROM … WHERE queries in Salesforce Inspector, you will find yourself relying less on complex Excel formulas and spending far less time building disposable one-off reports.
Install Salesforce Inspector or spin up the Web Console initially in a sandbox org, and run your first query today. Your future self (and your spreadsheets) will thank you.
Explore related content:
Can You Use DML or SOQL Inside the Loop?
Slack Code: AI Coding Agents Have Entered the Team Chat
Setup with Agentforce: What Admins Can Actually Do Right Now
#Chrome #Code #LowCode #SalesforceDeveloper #SalesforceHowTo #SalesforceTutorial #SOQL -
Agentforce Agent Flow Action Best Practices
I recorded an Agentforce hands-on video and published it on Salesforce Break YouTube channel in February of 2025. That video has been watched about 15K times until today. Then I participated in an Agentforce Hackathon at TDX, and published a video that sums up what our solution as a team looked like. Then I stepped away from building on Agentforce for a minute.
A lot has changed since then. If I leave the usual product renaming frenzy aside, Agentforce got a major face lift: Then new studio and builder are nicer. Many advancements have been rolled out. We have Agentscript now for deterministic solutions.
When MVP Sally ElGhoul invited me to do a Code with Sally session with her, I decided to revisit my Agentforce experience. Power Agentforce with Flow Actions session we recorded together dives into flow action best practices when building on Agentforce.
Let’s dive into the content, shall we. For those of you, who prefer video content, the video is embedded below.
What Powers Agentforce: AI, Flow, and Sub-Agents
Agentforce is Salesforce’s AI platform that completes transactions, beyond generating content and delivering predictions, forecasts, and next best actions. Agentforce powers an agent to update records, book a hotel, sell a product, even sign someone up for a class.
Salesforce groups Agentforce use cases into a few categories. Employee agents handle internal help. Service agents and sales agents cover external, customer-facing work. Under the hood, the terminology has shifted since I last built an agent. Topics are now called sub-agents. The Atlas reasoning engine still connects a user’s natural language prompt to the right sub-agent. Each sub-agent contains actions built from Flow, Apex, or prompt templates. Agents can even act as sub-agents inside other agents. That capability is still in beta.
Actions are not locked to a single sub-agent either. The same flow action can be reused across multiple sub-agents. That gives builders real modularity instead of duplicated logic everywhere.
Flow Actions vs Apex Actions in Agentforce
A natural question follows. With AI doing so much already, do developers still need Flow or Apex actions? Yes, we still need them.
Employee agents run in the context of the user submitting the prompt. They get access to a built-in Query Records action that runs SOQL or SOSL directly. Service and sales agents work differently; they run under a dedicated user instead of the running internal user. They can’t use the same query action.
Early versions of Agentforce sometimes fetched and exposed information that should have stayed private. Therefore Salesforce does not provide query access to external agents out of the box. A custom Flow or Apex action forces developers to make a deliberate choice: they must decide which fields and records an agent can see. Any action that performs a DML operation needs Flow or Apex as well. That means anything that creates, updates, or deletes records.
Inside the New Agentforce Studio and Builder
The old Agentforce builder lived strictly inside Setup. The new Agentforce Studio behaves more like the Automation app that houses flows. It sits outside Setup for users with the right permissions. It also offers a more polished, less click-heavy experience than before.
The new interface provides a pulldown on the screen that toggles between the canvas view and the script view. Builders can change between a visual layout and the underlying Agentforce scripting language.
Agentforce can generate a starting structure when given a prompt describing what the agent should do. It creates sub-agents and placeholder actions automatically but stops short of drafting an actual flow. Builders still have to create that flow themselves and connect it manually.
A few rough edges remain. The builder sometimes throws incorrect warnings on simple text (string) inputs, flagging them as though they need a Lightning-specific format when they don’t. Record collection variables can fail outright, requiring a manual fix in script view. Feedback shared in the Ohana Slack community also warns against using the new builder inside a namespaced org, where it reportedly doesn’t work reliably. The older builder remains available as a fallback.
Building Flow Actions That Power Agentforce Agents
Every flow action behind an Agentforce agent starts as an auto-launched flow with defined inputs and outputs. The descriptions attached to those variables are important. Agentforce pulls those descriptions in as the definitions shown on the agent side. Vague labels create vague, unreliable behavior.
Building in extra flexibility from the start also pays off. Adding a spare text input or output variable lets you adjust an action without deleting and rebuilding it, which used to be required any time inputs or outputs changed.
One key design decision is whether an action should stay narrow or flexible. It can do one specific thing, or it can handle several related tasks through a parameter. For anything performing a DML, the safer route is locking the action down to a single purpose. For read-only lookups, the demo took the flexible route instead, building one action that searches for accounts, opportunities, cases, or contacts based on a parameter. A second parameter controls whether the match needs to be exact or just a partial text match.
The action also returns a result string alongside its main output. That string carries success or error messages back to the agent, useful during testing for transparency and optionally shown to the end user, too. On the security side, one practice stands out: hand-pick which fields a flow returns rather than letting Salesforce auto-select them. That is the same best practice recommended for guest-user flows on a public community site.
Live Demo: An Agentforce Agent in Action
The demo featured a business development agent tied to a dedicated service agent user. Sub-agents included finding an account by name and retrieving its details. Others pulled open opportunities and calculated a close probability using a prompt template.
When asked to find an account containing “Acme,” the agent located it right away. It offered to show details, then offered related opportunities once the user confirmed. For the final step, a Flex prompt template reviewed the opportunity record. It also pulled in recent email and task activity, then returned a probability to close. In this live run, the agent returned 35 percent, explaining its reasoning by referencing recency of contact and the tone of recent interactions.
Grouping the “find account” and “get account details” actions under the same sub-agent made the sequence more reliable. Before that change, there was no guarantee the agent would always chain the steps correctly on its own.
Common Agentforce Questions Answered
Audience questions covered practical ground throughout the session, beyond just the demo. Here’s what we covered:
- Flow vs. Apex: Default to Flow first. Move to Apex only when Flow cannot handle the requirement. The deciding factor is long-term maintenance: does the organization have a developer on staff or under contract who can support Apex code going forward?
- Handling errors: Use fault paths for any flow that performs a DML. Pass a clear result back to the agent, either through a custom output variable or the flow’s built-in error message.
- Frequent errors in the new studio: A few options can help. Consult an AI assistant (e.g. Claude). Use Agentforce itself. Open a support case with Salesforce.
- AI-assisted flow development: Agentforce Vibes came up as a strong option, especially inside tools like VS Code.
- AI-generated flows and existing bugs: One attendee asked whether letting AI generate the underlying flow would fix the input and output errors shown earlier in the session. That likely wouldn’t fix the specific bug.
Flow and Apex are tools that fit different jobs, and AI can support both without replacing good judgment about which one to use.
Security and Permissions for Agentforce Agents
Every new agent in the demo org came with an automatically generated permission set. That set ties to a dedicated Einstein Agent user. The permission set controls which objects and fields the agent can see. It does not control record-level sharing.
Record-level access has to be handled inside the flow or Apex action itself. The permission set only governs object and field visibility, nothing more. The advice here is to test both positive and negative scenarios thoroughly: confirm that an agent can retrieve the right records, then confirm it cannot retrieve records it should not see.
Lessons From Breaking the Agentforce Demo
Near the end of the session, attendees requested a stress test of the agent. The request was a single, multi-step message: find the Acme account, list its details, find the open opportunity, and return the close probability, all at once. The first attempt confused the agent, handling some steps but not the full sequence. A second attempt came closer after tightening the sub-agent grouping. It still did not complete cleanly.
Sally ElGhoul used the moment to make a broader point about agent design. Agentforce agents rarely work perfectly on the first build. They require repeated testing with different phrasing. Builders need to pay careful attention to how instructions are written. The agent should be treated as a living project, not a one-time deployment.
Bring These Agentforce Lessons to Your Org
This session offered a grounded look at where Agentforce actually stands today, beyond the marketing pitch. Flow actions and Apex actions remain essential. That is not because AI cannot handle simple tasks. Salesforce intentionally requires developers to make deliberate choices about data access and security. The new Agentforce Studio is more usable than its predecessor. It still carries bugs around input and output variables that builders need to work around.
The live demo, including the moment it broke under audience pressure, illustrated the honest reality of building with Agentforce. Success depends on thoughtful action design and careful permissioning. It also depends on repeated testing with varied phrasing before anything reaches production.
Explore related content:
What Is Vibe Coding? And What’s New in Agentforce Vibes for Developers?
Setup with Agentforce: What Admins Can Actually Do Right Now
Headless 360: Developer Lessons From a Weekend of Building
#Agentforce #AgentforceStudio #AIAgents #Apex #SalesforceAdmins #SalesforceAutomation #SalesforceFlow #SalesforceHowTo #SalesforceSecurity #SalesforceTutorial -
Is Hardcoding Ids a Good Idea in Salesforce Flows?
Every Salesforce admin and developer has been tempted by the quick fix. You are building a Flow, and you need it to route an automated email to a specific queue, assign a task to a generic system user, or refer to a specific Record Type.
You open the record in your browser, copy the 15- or 18-character string from the URL (
0058W00000Gxxxx), paste it directly into a Flow text variable, and click Save. It works perfectly in your sandbox. You deploy it. Everything seems fine.There are many situations this approach fails, though.
Hardcoding Ids is one of the most common anti-patterns in Salesforce development. While it feels harmless in the moment, it creates fragile automation that is prone to catastrophic failure during deployments. Let’s break down exactly why this happens, how Salesforce handles Ids across environments, and the best-practice alternatives you should use instead.
The Root of the Problem: Data vs. Metadata
To understand why hardcoding fails, we have to look at how Salesforce separates Metadata (the structural bones of your org such as Flow definitions, custom fields, and page layouts) from Data (the actual records living inside those structures, like Accounts, Contacts, Users, and Queues).
When you deploy a Flow using a Change Set, DevOps Center, or a CLI tool, you are deploying metadata.
If your Flow contains a hardcoded Id pointing to a specific User or Queue record, you are embedding a data reference directly inside your metadata. The deployment tools will happily move your Flow structure to the target environment. But if that exact target environment doesn’t contain a record with that identical 18-character Id string, your Flow will throw an unhandled fault the second it runs.
Sandbox Creation: When Do Ids Match?
A common point of confusion is how Ids behave when you spin up or refresh a sandbox from your Production environment. Do the Ids copy over? Are they the same?
The answer depends entirely on whether you are looking at data or metadata, and what type of sandbox you are creating.
Metadata Ids (Record Types, Queues, Roles, Profiles)
When you create any sandbox from Production (Developer, Developer Pro, Partial Copy, or Full), Salesforce replicates your metadata layout.
Record Type Ids and DeveloperName values will match between Production and the newly created sandbox because Record Types are metadata.
Queue and Public Group Ids will also match initially because their structural definitions are pulled directly from Production.
Data Ids (Users, Accounts, Custom Object Records)
This is where things diverge significantly:
- Full Sandboxes: A Full Sandbox copies all metadata and all data records from Production. Consequently, the record Ids for your Accounts, Contacts, and Users will match Production exactly upon creation.
- Partial Copy Sandboxes: These copy a sample of your data based on a sandbox template. The records that are copied will retain their original Production Ids.
- Developer and Developer Pro Sandboxes: These environments copy zero data records from Production (except for standard Setup data like Users). If you create a brand-new Account record in a Developer Sandbox to test your Flow, it will generate a brand-new, completely unique ID that has absolutely no relationship to Production.
The Danger Zone: Disconnected Environments and Scratch Orgs
Even if you use a Full Sandbox where data Ids match Production perfectly, relying on hardcoded Ids is still a ticking time bomb. The risk skyrockets when your deployment pipeline introduces disconnected environments or scratch orgs.
If your team utilizes modern DevOps strategies such as Salesforce DX and Scratch Orgs, your environments are spun up completely from source code repository configurations.
A scratch org has absolutely no data relationship to your Production environment. When a scratch org is built, it is a completely blank canvas.
If your Flow expects a hardcoded User Id like
0058W00000Gxxxxto exist, it will instantly fail in the scratch org because that User simply does not exist. The same issue occurs if you have to manually recreate test records in a clean Developer sandbox; the text strings will never align across the pipeline.Furthermore, if a record is accidentally deleted in Production and recreated by an admin, it receives a brand-new Id. Your hardcoded Flow will instantly break, requiring an emergency deployment just to update a text string.
Best Practices: How to Avoid Hardcoding Ids
How do you build robust, environment-agnostic Flows that seamlessly transition from a scratch org to a sandbox, and ultimately to Production? Use these three reliable alternatives:
Use the Get Records Element (The Gold Standard)
Instead of hardcoding a Record Type Id or a Queue Id, use a Get Records element at the beginning of your Flow to query the system dynamically using a unique developer name.
Instead of: Filtering a record variable by RecordTypeId Equals
0128W000001xxxxDo this: Add a Get Records element looking at the Record Type object where
SobjectType Equals 'Account' and DeveloperName Equals 'Corporate_Account'. Then, reference the Id dynamically from that query step.Developer names are metadata; they remain identical across all environments, making your query 100% safe during deployment.
Leverage Custom Labels or Custom Metadata Types
If you must reference a specific system user or external integration Id that cannot be queried easily via a developer name, store that Id outside of the Flow.
Create a Custom Metadata Type or a Custom Label (e.g.,
Default_Task_Assignee_ID).Populate the label with the sandbox-specific Id in your sandbox, and reference that label inside your Flow using global variables:
{!$Label.Default_Task_Assignee_Id}.When you deploy the Flow, the metadata structure moves safely. You can then update the text value inside the Custom Label in Production manually or via deployment scripts without touching the core Flow logic.
Custom Settings can also be used for this purpose depending on your use case.
Use Global Variables for Profiles and Roles
If your Flow needs to validate a user’s Profile or Role, avoid hardcoding the Profile Id. Salesforce provides global system variables that let you look at the running user’s contextual information directly:
{!$Profile.Name}(e.g., Equals System Administrator){!$UserRole.Name}(e.g., VP of Global Sales)
Using names rather than hardcoded alphanumeric Ids ensures your logic remains readable, maintainable, and completely deployable.
A Quick Tip on Roles: Just like hardcoding IDs, checking
{!$UserRole.Name}directly in Flow logic can be risky if someone renames the Role in Setup. Where possible, checking Custom Permissions using{!$Permission.Your_Custom_Permission}is an even safer, more maintainable alternative!Read our post on custom permissions HERE.
Stop Hardcoding Ids: Build Deployment-Safe Flows Instead
Is hardcoding Ids ever a good idea? No. Never.
While it might save you two minutes during initial development, it passes an invisible technical debt down the line to your future self or your deployment team. By taking the extra moment to implement a dynamic query or reference a Custom Metadata Type, you ensure your Screen and Record-Triggered Flows remain unbreakable, no matter how complex your sandbox ecosystem or deployment pipeline becomes.
Explore related content:
Salesforce Flow Best Practices
Should You Use Roll Back Records in Salesforce Screen Flows?
Unanimous Flow Approvals – No More Workarounds
Open a Page Action: Redirect Users After a Screen Flow
#BestPractices #Code #LowCode #SalesforceAdmin #SalesforceDeveloper #SalesforceHowTo #SalesforceTutorial -
Should You Use Roll Back Records in Salesforce Screen Flows?
If you have ever built a complex Salesforce Screen Flow, you have likely run into this classic dilemma: Your user completes Step 1, clicks Next, and the Flow creates an Opportunity or an Account. But then, on Step 2, they hit an unexpected error, or worse, they simply close the browser tab.
Suddenly, you are left with orphan records or half-baked data cluttering your database.
Historically, fixing this required complex workarounds, such as building custom logic to manually delete created records if a subsequent step failed. But with Salesforce’s Roll Back Records element, you can hit the undo button on database changes automatically.
The question is: Should you use it in every Screen Flow?
Let’s dive into how it works, when it shines, and the critical edge cases you need to watch out for.
What is the Roll Back Records Element?
The Roll Back Records element gives admins transactional control over their Flows. It undoes DML operations, such as Create, Update, or Delete, made earlier in that transaction.
Think of it as an insurance policy. If a sequence of events cannot be completed perfectly from start to finish, the Roll Back element ensures the database reverts to exactly how it looked before the Flow started. No half-finished updates, no orphan records, no data debt.
The Golden Use Cases for Screen Flows
Screen Flows are uniquely vulnerable to partial data execution because they inherently invite human interaction. Here are the top scenarios where dragging a Roll Back Records element onto your canvas is an absolute must:
The Multi-Step Wizard with Dependencies
Imagine a Screen Flow where a user fills out a form to create a new Account, clicks Next, and is then prompted to add a Contact and an Opportunity. If the Account is successfully created, but the user gets a validation error on the Opportunity screen and abandons the Flow, you now have an Account floating around with no Contact and no pipeline.
By routing fault paths from your later screens and elements to a Roll Back Records element, you ensure that if the whole process can’t finish, none of it does.
Handling Complex Fault Paths Safely
We all know we should use Fault paths on our Data elements to give users a clean error message instead of an unhelpful unhandled fault screen. However, if your Flow has already executed a Create Records element before hitting that fault, showing a pretty error message doesn’t change the fact that data was already committed.
Image source: https://trailhead.salesforce.com/content/learn/modules/flow-implementation-2/roll-back-changes-after-an-errorA standard best-practice pattern for advanced error handling looks like this:
- A data element fails.
- The Flow triggers the Fault Path.
- The Flow hits the Roll Back Records element to clean the database.
- The Flow routes to a final Screen displaying a user-friendly error message explaining what went wrong.
Why should you always place your Roll Back Records element before the fault screen? Because if the user does not click next on the fault screen the roll back records would never execute if the elements are sequenced that way.
The Catch: Why You Can’t Use It Everywhere
While it sounds like a magic eraser, the Roll Back Records element has distinct guardrails. You cannot blindly add it to every Flow without understanding how Salesforce manages transactions.
The Realities of Flow Transaction Boundaries
What trips many admins up is understanding what actually constitutes a transaction boundary. In a Screen Flow, a transaction commits data every time the user hits a Screen, Pause, or Local Action. For example, if your Flow creates an Account record, then shows Screen 2, that Account is committed. If the Flow later fails updating a Contact and triggers Roll Back Records, the Account stays committed.
Image source: https://trailhead.salesforce.com/content/learn/modules/flow-implementation-2/roll-back-changes-after-an-errorThe rollback element can only undo uncommitted data changes within the current transaction. To make a rollback effective across multi-page forms, you must design your Flow to collect all user inputs across your screens first, and execute your DML elements sequentially at the very end of the Flow.
The Screen Component Blindspot
A Roll Back element reverts database changes, but it cannot revert user inputs on screen components or undo external system actions.
If your Flow executes an Apex Action or an HTTP Callout that sends data to an external ERP or billing system before hitting a Roll Back element, the Salesforce records will revert, but that external system will still have the data. External callouts cannot be rolled back by a Salesforce element.
The All or Nothing Rule
Roll Back Records is an uncompromising element. It rolls back all database changes made in the current transaction. You cannot tell it to roll back the Opportunity update, but keep the Account creation. If you need partial rollback capability, you have to architect your Flow carefully and handle all scenarios manually.
Best Practices for Salesforce Admins
If you are ready to start implementing Roll Back Records on Salesforce Break, keep these foundational rules in mind:
- Always end with a Screen: A Roll Back Records element is an end-state element; it terminates the transaction. However, you can route the path from the Roll Back element to a Screen component afterward. Always do this so the user understands that their changes were not saved and they need to try again.
- Keep transactions in mind: Remember that a Flow transaction pauses at a Screen element. If your Flow creates a record, passes a screen, creates another record, and then rolls back, it will roll back across those screen boundaries as long as it is part of the same overall Flow execution.
- Don’t substitute it for good validation: Roll Back elements are meant to handle unexpected system faults or user drop-offs. They should not replace standard validation rules or clear UI guidance that prevents bad data from being entered in the first place.
Put Roll Back Records to Work
Image source: https://help.salesforce.com/s/articleView?id=release-notes.rn_automate_flow_builder_roll_back_records.htm&release=234&type=5Should you use Roll Back Records in Screen Flows? Absolutely, but selectively.
For simple, single-screen Flows that update a single record, it is usually overkill. But for complex, multi-step wizards, junctions, or any Flow where a partial finish creates a data integrity nightmare, the Roll Back Records element is one of the most powerful tools in your admin toolkit.
Picture a multi-step wizard that collects a lead, then books an appointment. If the appointment creation fails, Roll Back Records undoes the lead creation too. The user simply starts over with a clean slate.
The Roll Back element can save you from writing complex cleanup automation and keeps your Salesforce org pristine.
Explore related content:
Salesforce Flow Best Practices
Open a Page Action: Redirect Users After a Screen Flow
Unleashing the Power of Editable Data Tables in Salesforce Screen Flows
The Ultimate Guide to the Salesforce Screen Flow File Preview Component
#SalesforceAdmin #SalesforceDeveloper #SalesforceHowTo #SalesforceTutorial #ScreenFlow #UI #UX -
Clean Data, Smart Flows: Automating Data Cleanup in Salesforce Nonprofit Cloud
I had the privilege of presenting at Nonprofit Dreamin, one of the most community-driven Salesforce events on the calendar. With a sold-out crowd of 300 participants, the energy in the room was exactly what you’d hope for when talking about technology that actually matters for mission-driven organizations. It was a great session, and the conversations that followed reminded me why this work matters. For everyone who attended, asked questions, or tracked me down afterward, thank you. Here’s a deeper look at everything we covered.
The Case for Clean Data in Nonprofit Cloud
Every Nonprofit wants to make decisions grounded in accurate, real-time data. But as any Salesforce professional knows, “accurate data” doesn’t just happen on its own. It requires deliberate architecture, thoughtful automation, and a clear understanding of which tools belong where.
In Salesforce Nonprofit Cloud (NPC), that challenge is multiplied. Built on the Salesforce Industries architecture, NPC introduces a purpose-built data model with Person Accounts, Gift Commitments, Gift Transactions, and volunteer management objects that all need to stay tightly synchronized. The good news? Salesforce Flow, especially with the addition of the Transform element, has become a powerful enough tool to handle both the data hygiene work and the complex calculations your fundraising and volunteer teams depend on, without touching your DPE credit limits.
This post covers two interconnected use cases: automating data sanitization for volunteer management and building advanced donor fulfillment calculations with Flow, including the new Transform element. Together, they demonstrate what’s possible when clean data and smart automation work in concert.
Why Clean Data Is the Non-Negotiable Starting Point
Before we get into calculations and check-in flows, let’s establish something foundational: none of this works without clean data.
In the Salesforce world, “clean data” means records that are accurate, consistent, and free of duplicates. For admins, this has always been best practice. But with the rise of AI Agents, autonomous programs that can execute real transactions inside your org, data quality has become a hard requirement. AI is only as good as what it’s grounded in. Garbage in, garbage out, and now that garbage can trigger a bad transaction at scale.
In NPC specifically, clean data is the backbone of reliable volunteer coordination, accurate donor reporting, and eventually, trustworthy AI-assisted fundraising. One of the most common, and most overlooked, data quality issues is mobile phone formatting.
Part 1: Automating Data Sanitization with Record-Triggered Flow
Volunteers check in using their last name and mobile phone number. That sounds simple until you realize that the same phone number can be stored dozens of different ways: (512) 555-0100, 512-555-0100, 5125550100, 512 555 0100. When a Get Records element tries to match on an exact value, any inconsistency breaks the lookup.
The fix is a record-triggered flow that strips all non-digit characters from the mobile phone field the moment a Person Account is created or updated.
Person Account
A person account is a Salesforce record type that combines Account and Contact into a single entity, allowing you to manage individuals like donors or volunteers without needing a separate business account record. NPC relies on Person Accounts as its primary constituent record.
The “Clean Mobile Phone” Flow
This flow runs when a Person Account is created, or when the mobile phone field is changed and is not blank. The sanitization logic uses a chained SUBSTITUTE formula that removes spaces, dashes, and parentheses in sequence, leaving only pure digits. The result: a consistent, matchable value in every record.
If you need flexibility, there are alternatives. Validation rules can reject improperly formatted entries at the point of save, preventing the problem before it’s created. Scheduled flows can run as a daily batch job to clean up any legacy data that snuck through before your automation was in place. For most organizations, a combination of all three provides the most airtight coverage.
Part 2: Reactive Screen Flows for Volunteer Check-In
Once your data is clean, you can build experiences that actually work. In NPC, volunteer management tracks jobs, positions, and shifts, and getting volunteers into the right slot quickly is a real operational challenge.
Rather than relying on a standard digital experience site, we built a custom screen flow that leverages reactive functionality: the ability for a screen to update dynamically based on user input without navigating to a new page.
Reactive Screen Flow
A reactive screen flow allows components on the same screen to communicate with each other in real time. A data table can update the moment a user types a search term or makes a selection, with no page reload.
How the Check-In Flow Works
The volunteer enters their last name and mobile phone number. Because we’ve already sanitized the phone field, the Get Records query finds an exact match reliably. If no match exists, a warning screen appears immediately.
From there, a data table displays available jobs, such as “Food Distribution.” Once the volunteer selects a job, a Screen Action triggers an auto-launched subflow in the background.
That subflow queries available shifts for that specific day and passes them back to a second data table on the same screen. The volunteer selects their shift and clicks Next, and the flow creates a Job Position Assignment record with a status of “Complete.” Clean, fast, no paper sign-in sheet required.
Part 3: Complex Donor Fulfillment Calculations with Flow and the Transform Element
With volunteers managed and data sanitized, let’s look at the other side of the NPC operation: donor management. Here, the goal is to give fundraising teams a real-time snapshot of donor health directly on the Account page.
Specifically, we want to calculate three things for each donor:
Current Year Gift Commitment: The donor’s pledge for the year. In NPC’s data model, this tracks promises rather than payments.
Current Year Paid Amount: The total actually received via Gift Transactions. A single commitment can have multiple transactions associated with it as the donor makes payments over time.
Fulfillment Rate and Membership Level: The percentage of the commitment that’s been paid, and a tiered classification (Gold, Silver, Bronze) based on actual payments.
Why Flow Instead of DPE?
NPC includes pre-built Data Processing Engine (DPE) calculations for Donor Gift Summary. Think of DPE as a mini-ETL tool built directly into Salesforce, designed to handle millions of records with joins, filters, and aggregations that would push a standard Flow to its governor limits. It’s powerful, but it comes with two significant constraints: a steep learning curve that many admins haven’t climbed yet, and a license-based DPE credit limit that can be exhausted quickly if calculations run in real time or too frequently.
Flow provides a low-code alternative that doesn’t count against those credits, making it the right choice for on-demand or daily updates across mid-sized datasets. The golden rule: always use the tool you already know if it fits the case at hand.
Step 1: The Auto-Launched Subflow
We start by building an Auto-Launched Flow to house all the calculation logic. Keeping the math in a subflow means the same logic can be triggered by a user button, a nightly schedule, or an automated event, without ever rebuilding it.
The flow takes three input variables: the Account ID we’re processing, a StartDate, and an EndDate. Formulas handle null inputs gracefully, defaulting to January 1st of the current year and today’s date respectively, so the flow still works if those values aren’t provided.
Two Get Records elements pull the data. The first retrieves Gift Commitments filtered by DonorId and EffectiveStartDate within the selected range. The second retrieves Gift Transactions for the same donor where Status is Paid and TransactionDate falls within range.
The Transform Element
This is where Flow Builder has meaningfully evolved. The Transform element allows you to map and aggregate data collections without the traditional Loop + Assignment pattern. Instead of iterating through every transaction record manually, we point the Transform element at the Gift Transactions collection, set the target to a currency variable, select Sum, and choose the Amount field. The element does the rest. Repeat the process for Gift Commitments.
This approach is bulkified by design and significantly easier to debug than a loop-based alternative.
Categorization via Formulas
A nested IF formula handles Membership Level assignment: Bronze for paid amounts under $50,000, Silver up to $100,000, and Gold above that. A separate formula calculates the Fulfillment Rate as a percentage. Both formulas include null checks to handle donors who have commitments but no transactions yet.
Step 2: The Screen Flow and Quick Action
The subflow handles all three rollups in a single execution: total paid amount, total commitment, and the derived fulfillment rate and membership tier. The Screen Flow itself grabs the Account ID from the page, passes it into the subflow, receives the calculated values back, and writes them to custom fields on the Account using an Update Records element. A Flow Message component displays a toast-style confirmation to the user when the calculation is complete.
Step 3: Nightly Automation via Scheduled Flow
A button is great for one-off checks. But data goes stale. The subflow architecture makes automation straightforward: a Schedule-Triggered Flow runs nightly at 8:00 PM, loops through all active donor Accounts, and calls the same subflow we built for the button. Every morning, the fundraising team logs in to dashboards and Account views that are already current.
Conclusion
Clean data and efficient automation are the engine of nonprofit effectiveness. Accurate volunteer check-ins mean accurate service records. Accurate service records mean accurate outcome data. And accurate outcome data is what allows organizations to apply for larger grants, deepen constituent relationships, and scale their mission year over year.
The same principle applies on the donor side. When gift fulfillment data is reliable and up to date, fundraising teams can have better conversations, identify at-risk donors earlier, and make the case for continued investment with confidence.
With NPC’s purpose-built data model and Flow’s growing capabilities, especially the Transform element, there has never been a better time to consolidate your automation strategy around tools your team already understands. The result is an org that’s not just manageable, but genuinely ready for whatever comes next, including AI.
Want to walk through these builds step by step? The Clean Data Playbook is available FREE on Flow Canvas Academy.
Explore related content:
Mastering Data Rollups in Nonprofit Cloud
What Nonprofits Taught Me About Building Salesforce for Humans, Not Just Systems
Salesforce NPSP vs Nonprofit Cloud Consultant Certifications
How the Salesforce Architecture Program Is Being Rebuilt with the Community
#Nonprofit #NonprofitCloud #NPC #NPSP #SalesforceAdmins #SalesforceDevelopers #SalesforceHowTo #SalesforceTutorials -
The Ultimate Guide to the Salesforce Screen Flow File Preview Component
The Spring ’26 Release introduced the File Preview Screen Flow Component. This native tool allows Admins to embed document viewing directly into the flow of work. In this post, we’ll explore the technical requirements, real-world observations, and the strategic implications of this functionality.
Beyond the “Files” Tab: Why This Matters
Historically, viewing a file in Salesforce required navigating to the “Files” related list, clicking the file, and waiting for the standard previewer to launch in a separate overlay. If you were in the middle of a Screen Flow, perhaps a guided survey or a lead conversion process, leaving that flow to check a document meant breaking your concentration.
Salesforce introduced a file thumbnail preview that shows visually what is in the file without having to click into it. Please note that the thumbnails show beautifully in the Single Related List component for lightning record pages. In the multiple related list view, I did not see the thumbnails.
In addition to the lightning record page and related list functionality, Salesforce introduced a file preview component that allows the user to see the preview of the file they have just uploaded, or they find attached to an object record in Salesforce.
Technical Blueprint: Configuring the Component
Setting up this component requires a shift in how Admins think about file data. Files data model is unique. To make the component work, you need to navigate the relationship between
ContentDocumentLink,ContentDocument, andContentVersion.Core Attribute Requirements
When you drag the File Preview component onto a screen in Flow Builder, you must configure the following:
Content Document ID (Required): This is the most critical field. The component needs the unique 18-character ID of the
ContentDocumentrecord. It will not accept theContentVersionID (which represents a specific iteration) or theAttachmentID (the legacy file format). Please note: the preview component always shows the latest version of the file.Label: This attribute allows you to provide instructions above the preview window. This is highly effective for compliance-heavy roles, where the label can say: “Verify that the signature on this ID matches the physical application.”
API Name: The unique identifier for the element within your flow logic, following standard alphanumeric naming conventions.
Using Conditional Visibility
Because the preview window takes up significant screen real estate, it should not be set to “Always Display”, if it will be driven by a data table reactively. Salesforce allows you to specify logic that determines when the component appears. You can set it to display only if a specific file type is selected in the collection and hide the component if the
ContentDocumentIDvariable is null to avoid showing an empty box.Lessons from the Field: Our “Around the Block” Test
In our recent hands-on testing, we put the component through its paces to see where it shines and where its boundaries lie.
The File Extension
The previewer is highly dependent on the browser’s ability to interpret file headers and extensions. During our test, we uploaded a standard log file. While the content was technically plain text, the file had a
.logextension. The component struggled to render this because it didn’t recognize it as a standard format. However, once we switched to a.txtextension, the preview was crisp and readable. The admin takeaway here is that if your business process involves non-standard file types, you may need to implement a naming convention to ensure files are saved in formats the previewer can handle: primarily.pdf,.jpg,.png, and.txt.Real-World Use Case
How can you use this component in a live production environment? Here is a scenario where the File Preview component adds immediate value:
Imagine a customer service representative handling a shipping insurance claim. The customer has uploaded a photo of a broken item. Instead of the agent navigating to the “Files” tab, the Screen Flow surfaces the photo on the “Review Claim” screen. The agent sees the damage, verifies the details, and clicks “Approve” all on one page.
Conclusion: A New Era of Flow
The File Preview component represents Salesforce being a holistic workspace. By integrating document viewing into the automation engine of Flow, Salesforce has empowered Admins to build tools that feel like custom-coded applications without writing a single line of Apex. As we saw in our testing, the component is robust and user-friendly. Most importantly, it keeps users focused. Whether you are streamlining an approval process or simplifying a complex data entry task, the ability to see what you are working on without leaving the screen is *chef’s kiss.*
Explore related content:
What’s New With Salesforce’s Agentblazer Status in 2026
Add Salesforce Files and Attachments to Multiple Related Lists On Content Document Trigger
Profiles and Permissions in Salesforce: The Simple Guide for Admins
#Automation #Salesforce #SalesforceAdmins #SalesforceDevelopers #SalesforceHowTo #SalesforceTutorials #Spring26 #Winter25 -
Should You Use Fault Paths in Salesforce Flows?
If you build enough Flows, you’ll eventually see the dreaded flow fault email. Maybe a record you tried to update was locked, a required field value was not set in a create operation, or a validation rule tripped your commit. Regardless of the root cause, the impact on your users is the same: confusion, broken trust, and a support ticket. The good news is you can catch your faults using the fault path functionality. In this post, we’ll walk through practical patterns for fault handling, show how and when to use custom error element, and explain why a dedicated error screen in screen flows is worth the extra minute to build. We’ll also touch on the roll back records element for screen flows where this functionality can make a difference.
Why Fault Paths Matter
Faults are opportunities for your Salesforce Org automation to improve. While unhandled faults are almost always trouble, handled faults do not have to be a huge pain in our necks.
The Core Building Blocks of Flow Fault Handling
1) Fault paths
Gets (SOQLs), DMLs (create, update, and deletes) and actions support fault paths. Fault paths provide a way for the developer to determine what to do in the event of an error.
2) Fault actions
You can add elements to your fault path to determine the next steps. You can also add a custom error element in record-triggered flows or error screens in screen flows for user interactivity. Multiple fault paths in the flow can be connected to the same element executing the same logic. A subflow can be used to standardize and maintain the fault actions such as temporarily logging the fault events.Logging Errors
Here is a list of data that may be important to include in your fault communications and logging:
- Flow label
- User Name
- Date/Time
- Technical details (e.g. $Flow.FaultMessage)
- Record Id(s) and business context (e.g., Opportunity Id, Stage)
- User-friendly message (plain English)
Subflow Solution
The advantage of a subflow when dealing with fault paths is that you can modify the logic once on a central location. If you want to start logging temporarily, you can do that without modifying tons of flows. If you want to stop logging, this change can be completed fairly easily, as well.
Inside the subflow, decide whether to:
- Log to a custom object (e.g., Flow_Error__c)
- Notify admins via Email/Slack
Meet the Custom Error Element
The Custom Error element in Salesforce Flow is a powerful yet often underutilized tool that allows administrators and developers to implement robust error handling and create more user-friendly experiences. Unlike system-generated errors that can be cryptic or technical, the Custom Error element gives you complete control over when to halt flow execution and what message to display to your users.
The Custom Error element lets you intentionally raise a validation-style error from inside your flow, without causing a system fault, so you can keep users on the same screen, highlight what needs fixing, and block navigation until it’s resolved. Think of it as flow-native inline validation.
What The Custom Error Element Does
It displays a message at a specific location (the entire screen or a specific field) and stops the user from moving forward. This functionality does present a less than ideal self-disappearing red banner message if you make a change to a picklist using the path component, though. Refrain from using the custom error messages in these situations.
The unique thing about the custom error message is that it can be used to throw an intentional exception to stop the user from proceeding. In these use cases, it works very similarly to a validation rule on the object.
This becomes particularly valuable in complex business processes where you need to validate data against specific business rules that can’t be easily captured in standard validation rules. For instance, you might use a Custom Error to prevent a case from being closed if certain required child records haven’t been created, or to stop an approval process if budget thresholds are exceeded.
Please note that custom error messages block the transaction from executing, while a fault path connected to any other element will allow the original DML (the triggering DML) to complete when the record-triggered automation is failing.
Custom Error Screen in Screen Flows
Incorporating a dedicated custom error screen in your screen flows dramatically improves the user experience by transforming potentially frustrating dead-ends into helpful, actionable moments. When users encounter an error in a screen flow without a custom error screen, they’re often left with generic system messages that don’t explain what went wrong in business terms or what they should do next, leading to confusion, repeated help desk tickets, and abandoned processes.
A well-designed custom error screen, however, allows you to explain the specific issue in plain language that resonates with your users’ understanding of the business process. Beyond clear messaging, custom error screens give you the opportunity to provide contextual guidance, such as directing users to the right person or department for exceptions, offering alternative paths forward, or explaining the underlying business rule that triggered the error. You can also leverage display text components with dynamic merge fields to show users what caused the problem turning the error into a learning moment rather than a roadblock. Additionally, custom error screens maintain your organization’s branding and tone of voice, include helpful links to documentation or knowledge articles, and pair with logging actions to give you valuable insights into potential process improvements or additional training needs.
Here is an example custom error screen element format (customize to your liking):
Error Your transaction has not been completed successfully. Everything has been rolled back. Please try again or contact your admin with the detailed information below. Account Id: {!recordId} Time and Date: {!$Flow.CurrentDateTime} User: {!$User.Username} System fault message: {!$Flow.FaultMessage} Flow Label: Account - XPR - Opportunity Task Error Screen FlowThe “Roll Back Records” Element
There are use cases in screen flows where you create a record and then update this record based on follow-up screen actions. You could be creating related records for a newly created record, which would require you to create the parent record to get the record Id first. If you experience a fault in your screen flow, record(s) can remain in your system that are not usable. In these situations the Roll Back Records element lets you undo database changes made earlier in the same transaction. Roll Back Records does not roll back all changes to its original state, it only rolls back the last transaction in a series of transactions.
Tips for fewer faults in the first place
Here are some practical tips:
- Validate early on screens with input rules (Required, min/max, regex).
- Use Decisions to catch known conflicts before DML.
- Place DMLs strategically in screen flows: Near the end so success is all-or-nothing (plus Roll Back Records if needed) or after each screen to record the progress without loss.
The fewer faults you surface, the more your users will trust your flows.
Putting it all together
Here’s a checklist you can apply to your next Screen Flow:
- Every DML/Callout element has a Fault connector.
- A reusable Fault Handler subflow logs & standardizes messages.
- Custom Error is used for predictable, user-fixable issues on screens.
- A custom error screen presents clear actions and preserves inputs.
- Technical details are available, not imposed (display only if helpful).
- Roll Back Records is used when it matters.
- Prevention first: validate and decide before you write.
Other Considerations
When you use a fault path on a record-triggered flow create element, and your create fails, please keep in mind that you will get a partial commit. This means the records that fail won’t be created while others may be created.
Example: You are creating three tasks in a case record-triggered flow. If one of your record field assignments writes a string longer than the text field’s max length (for example, Subject) and you use a fault path on that create element, one task fails while the other two create successfully.
Conclusion
My philosophy regarding fault paths is to add them to your flows, but never go down them if possible. When you see you are going down fault paths, then that means you have opportunity for improvement in your automation design.
Every fault you handle offers insight into how your flow behaves in the real world. Each one reveals something about the assumptions built into your automation, the data quality in your org, or the user experience you’ve designed. Treating faults as signals rather than setbacks helps you evolve your automations into resilient, reliable tools your users can trust. Over time, these lessons refine both your technical build patterns and your understanding of how people interact with automation inside Salesforce.
Explore related content:
How to Use a Salesforce Action Button to Validate Lookup Fields in Screen Flows
Should You Leave Unused Input and Output Flow Variables?
How To Build Inline Editing for Screen Flow Data Tables in Salesforce
Salesforce Flow Best Practices
Add Salesforce Files and Attachments to Multiple Related Lists On Content Document Trigger
#CustomErrors #FaultHandling #FaultPath #SalesforceAdmins #SalesforceDevelopers #SalesforceHowTo #SalesforceTutorials #ScreenFlows