Skip to main content

SalesPad Scripting: Creating and Managing Scripts - Knowledgebase / SalesPad for BC / Scripting - Cavallo Technical Support

SalesPad Scripting: Creating and Managing Scripts

Authors list
  • Product Development

SalesPad Scripting adds a low-code Script Designer inside Business Central where power users can arrange predefined steps to find records, check conditions, update fields, trigger BC’s custom AL codeunits, and more.  The Script Designer includes tests to dry run scripts without affecting live data, as well as a Copilot assistant to create, update, and interpret scripts with AI.

Table of Contents

How do I install SalesPad Scripting?

Simply locate the SalesPad Script Manager extension on the BC marketplace and install it for your BC environment.  All setup steps and configuration options can be found within BC, including global settings, script management permissions, script assignments, and the Script Designer.  SalesPad Scripting is free to test in sandbox environments; contact Cavallo to get licensing for your production environment.

Which BC version is needed?

SalesPad Scripting requires Business Central version 26 (2025 release wave 1) or later.

Does it need any outside servers or services?

No, everything runs inside BC. The only outside piece is the Copilot assistant for building scripts with AI, and this is optional and connects to your Azure OpenAI resource.

Do I need a license to use scripts?

Yes, production environments require a valid, active license with Cavallo. The check runs automatically in the background every time you create, edit, or release a script.

Do I need a license to test in sandbox?

No, sandbox environments are always fully licensed.  You can build, edit, and release scripts freely in any sandbox for evaluation, development, and testing without a license.

Where do I manage my license?

The Cavallo License Management page in BC provides visibility of all Cavallo SalesPad licensing.  You can review existing licenses and activate / renew licenses from this page.

What happens if my license expires?

Released scripts keep running even if your license lapses.  Licensing only blocks new authoring; it does not stop existing on-save and run scripts from executing, so a lapsed license cannot interrupt live business processes.

How do I manage script access?

SalesPad Scripting has global settings that determine script behavior across Business Central, permission sets to control who can create and manage scripts, and script assignments that decide which users and third-party applications have access to which scripts.

Are there global settings for scripts?

Global script behavior is managed in the SalesPad Script Configuration page.  These settings control logging, error notifications, and Copilot configuration options.  Users must have the “SalesPad Script Setup Admin” or “SalesPad Script Admin - Full Access” permission set to make changes to these settings.

Category

Setting Name

Description

Logging

Enable Logging

When enabled, every script execution will save its full trace log.  Each trace ends with a Run Statistics line showing how many SQL statements ran, how many rows were read, and how long the run took.  Errors are always logged regardless of this setting.

Error Notification

Error Notification Email

Provide an email address to receive notifications when scripts encounter unexpected errors.  Leave blank to disable email notifications for errors.

Email Account

Choose which registered email account sends error notifications.  Leave blank to use the tenant’s default email account.

Reports

Default Report Row Limit

Set the starting Max rows for new Add Report Row blocks in quick reports; each block can raise or lower it.  Defaults to 1,000 rows.  Reports that reach the row limit will display that some rows were omitted.  Set to 0 for no limit.

Report Email Account

Choose which registered email account sends reports from scripts that use Quick Report with Email Report turned on.  Leave blank to use the tenant’s default email account.

 

How do I enable the Copilot assistant?

The Copilot assistant requires connecting an Azure OpenAI resource.  Because SalesPad Script Manager is a third-party extension (not Microsoft-published), it cannot use Microsoft's built-in First Party authorization for AI features, so you must connect it via the Configure Copilot global settings.  The Azure OpenAI usage is billed to your Azure subscription.

Configure Copilot

Azure OpenAI Endpoint

Provide your Azure OpenAI resource endpoint URL.

Deployment Name

Set the deployment name of the chat model that Copilot will use.

API Key

Set the resource’s API key.  After saving, this value is masked, and API Key Set will be turned on.  After the initial save, leave this field blank to keep the currently saved key.

API Key Set

Automatically turns on once the API Key is saved.

 Copilot is only used by SalesPad Scripting as an AI assistant for building scripts.  It can explain scripts in plain English and propose changes to scripts based on your instructions.  It cannot release scripts on its own, and it does not trigger when scripts run.

Copilot can be enabled or disabled for each BC environment on Business Central's native Copilot AI Capabilities admin page ("SalesPad Script Builder").

How do I control who manages scripts?

SalesPad Scripting has permission sets to control who can create, assign, and manage scripts.  Admins can have access to everything, while other people get only the access they need.  These permission sets do not control access to individual scripts; that is handled by script assignments.

Permission set

Who it’s for

What it grants

SalesPad Script Authoring Admin

Script builders

Create and edit scripts, operations, and parameters, and use the Copilot assistant

SalesPad Script Assignment Admin

Access administrators

Assign and remove which user profiles and Entra applications can run which scripts

SalesPad Script Log Admin

Support / monitoring staff

View execution logs, background job results, and script run history

SalesPad Script Setup Admin

System administrators

Configure global scripting setup and Copilot settings

SalesPad Script Quick Report (CAVScriptQuickReport)

Report users

Open the SalesPad Quick Reports page and run quick reports assigned to their role.  Not needed to run a quick report from a record page

SalesPad Script Admin - Full Access

Power users / scripting admins

Everything above for full management access

SalesPad Script Manager - Execution API (CAVScriptExecApi)

External integrations (e.g. Mission Control)

Execute-only access to the CavalloScriptExec webservice endpoint

How do I control who can run scripts?

Script assignments control who is allowed to use a script.  Scripts can be assigned to one or more user profiles (Role Center profiles, e.g. Warehouse Worker or Sales Rep) and Entra applications (service accounts, e.g. API integrations or automated jobs).  Profiles and applications can be assigned any number of run scripts and quick report scripts, and one On Before Insert and one On Before Modify script per source table.  For more explanation on script types, refer to this section.

Run scripts can be assigned to any number of user profiles and Entra applications.  Those profiles’ users can run those scripts on demand in BC, and those Entra applications can trigger those scripts as part of their processing.

Quick report scripts are assigned the same way as run scripts.  Users can run their assigned quick reports from the SalesPad Scripts menu on a record page, or from the SalesPad Quick Reports page, which requires the SalesPad Script Quick Report permission set.

Each user profile or Entra application can only trigger one On Before Insert script and one On Before Modify script per source table.  Applying a new On Before Insert script for a user profile that already had a script for that same table will automatically replace the older script assignment.  The same source table can have different automatic behavior for different profiles and applications based on their assigned scripts.

How do I assign scripts?

Scripts can be assigned in the Script Designer, the SalesPad Script Assignments page, the user profile card, or the Entra application card.  These pages provide ways to quickly assign out scripts once they’re created and manage script assignments for user profiles and Entra applications.

To assign a script via the Script Designer: launch a script, and in the Actions dropdown at the top left, select Assign Script, then either user profile or Entra application.  Either option opens a multi-select list so you can create one or more assignments at once.  This is the fastest way to assign scripts when you already have the script open and want to hand it out to several profiles or applications at the same time.

To assign a script from the Script Assignments page: launch the page, find the user profile or Entra application, click the Assign Script button, and select a script to assign it to that profile application.

To assign a script from the profile or application card: launch the user profile or Entra application, find the Assigned Scripts section, click the Assign Script button, and select a script.  Scripts can also be removed from profiles and applications here.  Removing a script this way only removes the assignment; it does not delete or unrelease the script itself.

If a profile or application is deleted, its script assignments are cleaned up automatically; no need to delete them beforehand.

Note that helper scripts are never assigned directly, because they are always called by other scripts.

How do I create scripts?

From the SalesPad Scripts page, click the New button to launch the Script Designer.  Fill out the General fields for the script to set the base structure, then you can start building blocks to control the script logic.  Script blocks are visually nested to show how conditional logic and loops shape the processing flow.  

General Script Field

Field Description

Name

Set the title for the script

Description

Set a summary of what the script does

Script Type

Set the type: Run Script, On Before Modify, On Before Insert, Quick Report, or Helper Script

Status

Set the status: Draft or Released

Source Table No

Select the source table for scripts that trigger for a specific record type (e.g. Sales Header)

Source Table Name

Automatically populates based on the selected Source Table No

 

Which script type should I choose?

Run scripts can be triggered manually by users on BC pages and by third party integrations, and automated on a schedule or as documents move in Mission Control workflow.  On Before Insert and On Before Modify scripts run automatically when records are created or changed.  Quick report scripts read records and build a report to email or show on screen.  Helper scripts are called by other scripts to perform the same logic in multiple situations.

What can run scripts do?

Run scripts can be assigned to a record type.  This controls the BC cards where users can see and run them, and the Mission Control workflows where they can be incorporated.  An example would be a script tied to sales quotes which combines all open quotes for that same customer so they can become a single consolidated order.  Note that triggering run scripts in workflow requires Mission Control to be installed.

When run scripts are not assigned to a specific record type, they are not available on cards or workflows, but they can be set up to run automatically on a schedule.  An example would be a script that runs nightly to load all customers, check their balance against their credit limit, and update credit check flags so the team can review them the next day.

Making a run script available for a third-party application to invoke requires setting it up as an Entra application in BC, then assigning it that script.

Examples:

  • Run a price check comparing the order’s current line item pricing to the customer’s contract and automatically update as needed to respect the contract

  • Trigger automatically when a quote enters the Approved workflow queue, load other approved quotes for the same customer, and combine them onto a single order for shared fulfillment

  • Calculate fields based on other data provided on the order and its lines

  • Cascade updates from a master record to related documents

What can On Before Insert scripts do?

On Before Insert scripts trigger when a new record is saved.  This is where you can set default fields for new documents automatically, and prevent new records from being created if they don’t meet certain criteria.  For example, if a new sales order doesn’t have a Location Code set, then the save can be cancelled and a popup message can tell the sales rep to set the warehouse location.

Examples:

  • Populate the customer’s default vendor on their new orders

  • Ensure all required fields on new quotes are filled out

  • Generate sequence numbers or codes

  • Validate or set custom fields based on business logic

Due to how BC save processing works when users manually create orders, On Before Insert is more applicable for integration import type operations.  On Before Modify is the best bet for manual order entry scripts.

What can On Before Modify scripts do?

On Before Modify scripts trigger when changes to an existing record are saved.  You can compare the new field values to the old values and prevent saving those changes.  For example, if the sales order’s Status has changed from Open to Released, and that order doesn’t have any line items, then the save can be cancelled and a popup message can tell the sales rep that orders must have at least one line item to be released.

On Before Modify scripts have two available reference objects: REC is the current state of the record with all changes made by the user, and XREC is the database state before modifications.  This lets you see what has changed and perform specific validation and processing based on those updates.  It is highly recommended to use explicit condition operations to gate actions based on field changes.  For example, use [REC.Status] <> [XREC.Status] to ensure that the order’s status has been changed before performing other validation; that way the script is not doing all of its validation every time the order saves, only when it is necessary.

Examples:

  • When the order status is set to Released, validate that other required fields are filled out

  • Send notifications when the order status changes from Open to Released

  • Update related records when key fields change

  • Cascade updates to child documents

What can quick report scripts do?

Quick report scripts generate simple grid reports that can open on screen or email as an Excel or CSV attachment.  They can be run from the SalesPad Scripts menu on a record page, or from the SalesPad Quick Reports page, which lists every released quick report assigned to the user’s role.  Quick report scripts can’t be triggered from Mission Control or the API.

Quick report scripts never change data, so they can only use certain blocks: Quick Report, Add Report Row, Load Entity, Load Entities, Declare Variable, Set Variable, If / Else If / Else, Log Message, and Raise Error.

What can helper scripts do?

Helper scripts are reusable building blocks that other scripts can call.  This puts shared logic inside one helper script, so multiple scripts can trigger that same processing.  When the shared logic needs updates, it is adjusted in the helper script, and every related script immediately gets those changes and follows the new rules.  Every helper script can have its own parameters so other scripts can send information that the helper script will use.  

Examples:

  • Perform a credit check the same way for all customer-related scripts and order-related scripts

  • Use the same formatting and structure for every run script that needs to send a notification

  • Copy a sales line and properly set all fields for every situation that needs to copy lines

Which source table should I choose?

For on-save scripts, select the table that should trigger this script’s logic when records are inserted or modified.  For run scripts and quick report scripts, select the table that corresponds to the pages where this script should be available.  For run scripts and quick report scripts that will run on a schedule, or quick report scripts that should run from the SalesPad Quick Reports page, leave the source table blank.  

Automatic on-save scripts are available for:

  • Customers

  • Sales quotes, orders, invoices, and returns, and their line items, including posted invoices and shipments

  • Vendors

  • Purchase orders and line items, including posted invoices and receipts

  • Items

  • Warehouse shipments and picks, and their line items

  • Transfer orders and line items

  • Service quotes, orders, and invoices, and their line items

  • General journal lines

The SalesPad Scripts menu, with its Run Script and Quick Report actions, is available for:

  • Customers

  • Sales quotes, orders, invoices, and return orders, and their line items

  • Vendors

  • Purchase orders and line items

  • Items

  • Warehouse shipments and line items

  • Transfer orders and line items

  • Service quotes, orders, and invoices, and their line items

  • General journals

  • Item ledger entries

The following pages support run scripts out-of-the-box:

Page

Source Table

Customer Card

Customer

Vendor Card

Vendor

Item Card

Item

Sales Quote

Sales Header

Sales Quote Subform (lines)

Sales Line

Sales Order

Sales Header

Sales Order Subform (lines)

Sales Line

Sales Invoice

Sales Header

Sales Invoice Subform (lines)

Sales Line

Sales Return Order

Sales Header

Sales Return Order Subform (lines)

Sales Line

Purchase Order

Purchase Header

Purchase Order Subform (lines)

Purchase Line

Warehouse Shipment

Warehouse Shipment Header

Warehouse Shipment Subform (lines)

Warehouse Shipment Line

Transfer Order

Transfer Header

Transfer Order Subform (lines)

Transfer Line

Service Order

Service Header

Service Order Subform (service item lines)

Service Item Line

Service Lines

Service Line

Service Quote

Service Header

Service Quote Subform (service item lines)

Service Item Line

Service Quote Lines

Service Line

Service Invoice

Service Header

Service Invoice Subform (lines)

Service Line

Service Item Worksheet Subform (lines)

Service Line

General Journal

Gen. Journal Line

Item Ledger Entries

Item Ledger Entry

 

Where do I build the script?

Below the General section, the Operations section controls the script logic.  The toolbar across the top of this section shows indicators for unsaved changes and read-only mode, and it provides buttons for Undo, Redo, Validate, and Save.

The palette on the left lists every possible operation, grouped into Records, Fields & Variables, Control, Messages, Errors, Integration, and Reports (quick report scripts only).  Some operations have a code-style caption in the palette: Load Entity is “If FindFirst()” and Load Entities is “If FindSet()”.  Elif and Else aren't in the palette — they are added with the “+ Else If” and “+ Else” buttons on the footer of the block they follow.

The canvas in the middle is where you arrange blocks to form your script.  The hat block at the top shows the script's trigger, source table, and parameters for helper scripts.  Underneath, the processing blocks display and update as you change the General fields or the helper's parameters.

The panel on the right has two tabs.  The Details tab edits the selected block, while the Copilot tab provides access to the AI scripting assistant.

What are script operations?

Script operations are prebuilt logic blocks that you combine to build scripts.  Each operation contains code to perform a specific action.  You drag these options from the palette onto the canvas, arrange them, and set their details to control how they work and what they do.

Load Entities

Record operations handle loading, creating, updating, and deleting records.  

  • Load Entity: “If FindFirst()” searches for a specific record, loads the first match, and only runs its child blocks if it found a match.  

  • Load Entities: “If FindSet()” searches for a list of records, loads them all, and loops through its child blocks to trigger the same processing for every match in the list.

Both load operations have required details:

  • Entity name: how you’ll reference the loaded record later, e.g. CHECK_LINE

  • Table: the source table to load from, e.g. 37 - Sales Line

  • Filter: the where clause to find matching entities, e.g.
    WHERE(
    “Document Type”=FILTER([REC.”Document Type”]),
    “Document No.”=FILTER([REC.”No.”]),
    “Type”=FILTER(‘ITEM’)
    )

Both load operations can have Else blocks to trigger certain logic if no matching records are found.  This is helpful for showing messages or throwing errors when expected records are not found, or triggering alternate logic based on checks that involve loading records.

It is important to note that nesting a Load Entities inside another Load Entities has multiplicative effects.  For example, loading 10 lines, and then loading 3 vendor records for each line, causes 30 total vendor loads.  Use Test Total Count to measure this before running against large datasets.

Create Record

The Create Record operation creates a new record in the specified table.  Set the source table where the new record will be created and the entity name to use for referencing the created entity, and then add child Set Field blocks to set the information on the record before it is saved.

Save Record

The Save Record operation saves a record immediately instead of waiting for it to leave scope.  A record created with Create Record is inserted; a loaded record with pending Set Field changes is modified. The entity stays in scope afterwards, so later operations can read values assigned by the save (for example a No. assigned from a number series).  

This operation cannot be used with the source entity (REC); it is intended to be used when a loaded or created entity must be saved so that a later operation can use the saved record.  For example, save a new order to generate its document number before creating its lines so the document number can be assigned to each line.

If a record is saved by one Save Record and then saved again by another Save Record, that record is modified by the second save, not inserted a second time.  Dry runs never save anything to the database, and the execution log shows what would be saved.

Delete Record

The Delete Record operation deletes a record immediately.  This can affect records that were loaded via Load Entity or Load Entities, or it can affect the source record (REC) itself.  Note that XREC is read-only and cannot be deleted.  This runs the table’s standard deletion logic, so it will fire On Delete triggers, and standard BC delete errors (e.g. a customer with ledger entries) are raised as normal.

Inside Load Entities, the delete runs once per iteration, removing every matching record.  Dry runs never delete anything, and the execution log shows what would be deleted.

Set Field

The Set Field operation assigns a value to a field on a loaded record.  Select the target entity, target field, and the value to be assigned.  The value can be a literal, a field reference, or an arithmetic / string script.  When the script runs, the changed record is marked as modified.  The actual database write is deferred to the end of the script, or to the end of the current iteration for Load Entities loops.

Values must match the field’s type.  The editor will show a warning for type mismatches, and if the script runs it will throw a “Cannot assign” error.

Target type

Accepts

Valid values

Clear field value

Invalid values

Text, Code

Any value formatted as text

‘Approved’

‘’

 

Option, Enum

The caption or member name in quotes

‘Released’

‘’

An unknown caption

Integer, BigInteger

A whole number

15

0

‘5’ (text), 2.5 (use ROUND())

Decimal

A number

2.5

0

‘5’, ‘2.5’ (text)

Boolean

A Boolean field, true, false, a comparison in parentheses

true

([REC.Amount] > 0)

false

‘Yes’, ‘true’, 1

Date

A Date field, DATE(), a calculated date

DATE(‘2026-10-15’)

System.Today() + 7

0D

'2026-10-15', '10/15/26', a datetime (use DATE())

Time

A Time field, TIME()

TIME(‘08:30:00’)

0T

'08:30:00'

DateTime

A DateTime field, a calculated datetime

DATETIME(‘2026-10-15’, ‘17:00:00’)

System.CurrentDateTime()

0DT

'2026-10-15 17:00:00', a date

 

Tips for literals:

  • Text goes in single quotes. To put a quote inside text, double it, as in AL: 'it''s done' is the text: it's done.

  • Numbers are written with . for decimals and no thousands separator, e.g. 1234.5. This is the same for every user, regardless of their language and region.

Field reference examples:

  • Set Field [REC."Shipping Name"] := [REC."Sell-to Customer Name"]

  • Set Field [lines."Unit Price"] := [item."Unit Price"]

  • Set Field [REC."External Document No."] := [REC."No."]

Arithmetic examples:

  • Set Field [lines."Line Amount"] := [lines."Quantity"] * [lines."Unit Price"]

  • Set Field [REC."Total with Tax"] := [REC."Amount"] * 1.07

  • Set Field [REC."Discount Amount"] := [REC."Amount"] * ([REC."Discount %"] / 100)

  • Set Field [item."New Price"] := [item."Unit Cost"] * 1.5 + 10

Tips for arithmetic:

  • -, *, and /, and the functions MIN, MAX, ROUND, and ABS, take numbers only.  Text is not converted automatically, so use DECIMAL() to convert text first.

  • + can be used for text, but it will concatenate the text instead of performing arithmetic, which can produce unexpected results if you don’t convert types properly.  The editor shows a yellow warning when + will join values as text that you probably meant to add, for example 'Total: ' + [A] + [B].  When you mix text and arithmetic, wrap the arithmetic in parentheses, for example: 'Total: ' + ([A] + [B]).

  • Code and text fields are treated as text, even when they hold digits, so must be converted before being used as numbers.

  • Combine multiple operations using parentheses for precedence, e.g. Set Field [REC."Net Amount"] := ([REC."Gross Amount"] - [REC."Discount Amount"]) * 1.07.

  • Comparisons are strict: both sides must be the same type, or the script stops with a “Cannot compare” error.  Compare a Code field with quoted text, and compare dates with DATE() rather than quoted text.

Press Ctrl+Space to see the list of functions:

Function

Result

ROUND(value, [digits])

Rounds to digits decimal places, or to a whole number if digits is omitted

MIN(a, b)

The smaller of the two numbers

MAX(a, b)

The larger of the two numbers

ABS(value)

The absolute value (makes negatives numbers positive)

FORMAT(value, [length], [format])

The value as text, like AL Format(), e.g. FORMAT(System.Today(), 0, '<Year4>-<Month,2>-<Day,2>')

DECIMAL(value)

Text converted to a number

DATE(value)

Text in yyyy-MM-dd format, or a datetime, converted to a date

TIME(value)

Text in hh:mm:ss or hh:mm format, or a datetime, converted to a time

DATETIME(date, [time])

A datetime in the user’s time zone, like AL CreateDateTime, with time set to midnight if time is omitted

System.Today()

Today’s date

System.CurrentDateTime()

The current date and time

UserSecurityId()

The User Security ID (a GUID) of the user running the script, e.g. load the user’s record with WHERE("User Security ID"=FILTER(UserSecurityId()))

 

Type . after a text value to see methods that can be used for it:

Method

Result

Example

.Contains(value)

true if the text contains the case-sensitive value

[REC."External Document No."].Contains('WEB')

.StartsWith(value)

true if the text starts with the case-sensitive value

[REC."No."].StartsWith('C')

.EndsWith(value)

true if the text ends with the case-sensitive value

[item."No."].EndsWith('-RED')

.Split(separator).Get(index)

One part of the text after splitting it based on the separator, index starts at 1 for the first part

'ABC-123-RED'.Split('-').Get(2) gives ‘123’

 

Declare Variable

The Declare Variable operation creates a new variable that can be set and referenced throughout the scope where it is initialized.  For example, when adding new sales lines to an order, you can first declare a Line_Number variable, then for each line that is added you can assign the current Line_Number (e.g. 10000) and then increment Line_Number to the next value for the next line (e.g. 20000).

Set Variable

The Set Variable operation updates the value for a variable that was created with the Declare Variable operation.  For example, a loop operation like Load Entities can update a variable based on the latest loop completed, and the next loop can use that value and update it again with Set Variable. 

If, Else If, Else

The If operation performs different logic based on certain conditions.  It does a defined check, and it only triggers its child blocks if that check passes.  The If block’s footer provides options to add Else If and Else blocks.  Else If blocks trigger their own sections of the logic only if their check passes and all prior Ifs and Else Ifs failed their checks.  Else blocks trigger their child blocks only if all prior Ifs and Else Ifs failed their checks.

This allows you to trigger specific logic based on different possible states and values.  For example, you can check if the order number ends in .1 and run logic based on that, and otherwise check if the order number ends in .2 and run different logic based on that, and otherwise throw an error because the order number must end in either .1 or .2.

Condition expressions can combine comparisons and boolean logic:

  • Comparison operators: =, <>, >, <, >=, <=

  • Boolean operators: AND, OR

  • Grouping: Parentheses for complex logic

  • Field references: [entity."Field Name"] for runtime values

  • Literals: Numbers, strings (in single quotes for text), booleans (true/false)

Examples:

  • If [item."Lead Time (Days)"] > 5
      └─ Set Field [REC."Expedite Flag"] := true

  • If [REC."Status"] = 'Posted' AND [REC."Amount"] > 1000
      └─ Raise Error "Cannot modify large posted transactions"

  • If ([REC."Discount %"] > 10 OR [REC."Customer Type"] = 'PREMIUM') AND [REC."Approved"] = true
      └─ Set Field [REC."Special Handling"] := true

Note that condition expressions (used in If and Else If) are different from filter scripts (used in Load Entity and Load Entities). Conditions use AND/OR keywords for boolean logic, while filters use comma-separated fields for AND and | within values for OR.

Confirm Dialog

The Confirm Dialog operation prompts the user to respond to a yes-or-no question and then performs different logic based on their answer.  Enter the question to ask, which can reference currently in scope variables and entities.  Add child blocks to trigger specific processing when the user answers yes.  In the footer of the Confirm Dialog block, optionally add an Else block with its own child blocks to perform different processing when the user answers no.  If nothing needs to happen when the user chooses no, then don’t add an Else block.

Headless operations (running in the background, automated, or when an integration calls a run script) cannot be prompted to respond yes or no.  They default to triggering the no path logic, but they can be flipped to default to yes by flagging the checkbox for “Answer yes when nobody can be asked (background runs)”.

Call Helper Script

The Call Helper Script operation triggers a specific helper script and passes certain values for the helper script’s parameters.  The helper script performs its processing, which can load, create, and update records, and it can also change the passed parameters so they are different when the calling script continues with its own processing afterwards.  

Refer to the section on helper scripts for more information on creating and calling them.

Run Codeunit

The Run Codeunit operation invokes a BC codeunit, extending the script with custom AL logic.  Select the codeunit to run and the record to pass.  It is important to note that Run Codeunit does not trigger when running the dry run tests in the Script Designer actions, because codeunits can make changes to live data which scripts cannot roll back.

Log Message

The Log Message operation adds a message to the execution log.  This is helpful for adding extra auditing or debugging logs.  Simply set the message to be logged, which can reference in-scope entities and variables.  For example: 'Processing item ' + [REC."Item No."] + ' with Unit Price: ' + [item."Unit Price"].

Show Message

The Show Message operation does the same logging as the Log Message operation, and it also displays that message to the user in a popup.  In headless executions (automations, integrations calling run scripts), the message is still written to the log but no popup is shown.  For example: ‘Split based on reservations -> ‘ + [RESERVED_DOC_NO] + ‘ & ‘ + [UNRESERVED_DOC_NO]

Show Banner

The Show Banner operation does the same logging as the Log Message operation, and it also displays that message in a dismissable notification banner at the top of the page.  Because this doesn’t block the user from interacting with the page, it is less intrusive than Show Message.  Like Show Message, for headless executions the message is still written to the log but no popup is shown.  For example: 'Order ' + [REC."No."] + ' processed successfully'

Quick Report

The Quick Report operation can only be used for quick report scripts.  It builds a table from the records that the script loops through, then shows the table on the screen or emails it.  Add the Quick Report block and then Load Entities within it and Add Report Row for each row that should be displayed in the report.

To email the report instead of showing it, flag the Email report checkbox, enter an Email To, and choose whether to attach as Excel or CSV.  The Email To can be a plain text email address like ‘[email protected]’, or a field from the currently in scope variables like [REP.”E-Mail”].

To run and view quick reports in BC, launch the SalesPad Quick Reports page from the SalesPad Scripting menu.  This lists all quick reports that are released and assigned to the current user’s profile.  Users who have script editing permissions can click the quick report’s Name to view the script information.  To generate the report, select it in the list and then click the execute button.

If the quick report has a source table then it will show a popup to select a specific record; otherwise, the report loads immediately.  The report page shows all added rows, with columns in the same order that they were defined in the Add Report Row block.  If there were multiple nested report rows, then you can select one parent record to see its children.  For example, select the sales document to see its line items.  You can Export to Excel to download the report.

When the quick report should be emailed, the report is sent from the Report Email Account as an attachment.  When sent as Excel, each group of detail rows is a collapsible row group under its parent row.  When sent as CSV, all rows are completely flat for importing into other tools, so there will be one header row with every level’s columns and then one line per detail row with all parent row values repeating.  Values are written in a locale-neutral format (e.g. 2026-10-19, 1234.5).

A Quick Report block inside a loop builds one report per iteration, for example one email per customer.  A quick report can't be inside another quick report. For rows under rows, nest Add Report Row blocks inside one Quick Report block instead.  A report with no rows is not emailed, and a report shown on screen displays a “No rows found” message instead.

Each Add Report Row block has a Max Rows limit, which starts at the Default Report Row Limit from the global settings.  On a top-level row block, Max Rows restricts the total parent rows; on a nested one, it restricts per parent row.  Set it to 0 or leave it empty for no limit.  When a row block reaches its limit, the loop it is in stops reading records, and the report notes that some rows were left out.  To choose which rows are kept, add a sort order to the load’s filter, for example SORTING("Due Date") or ORDER(Descending).

Showing a report requires a user.  Headless execution (running in background, automated, run scripts called from an integration) stops with an error if a quick report should be shown and not emailed.  Dry runs will show the report but will not email it.

Add Report Row

The Add Report Row operation adds one row to the Quick Report block that it is inside.  In the Details pane, add the columns for the row.  They will show in the same order that they are displayed here, and they can be rearranged by dragging them by their handle on the left.  Up to 20 columns can be displayed in a quick report.

Tips for columns:

  • Column values are calculated at this block, so they can use the entities of every loop the block is inside, for example [CUST."No."] and [DOC."No."] together.

  • The type defaults to Auto: the column takes the type of its value, and the designer shows what that is, for example Auto (Decimal). Pick a type to force one — Integer for whole numbers that aren't an Integer field, such as arithmetic or a typed-in number (Auto makes those Decimal), or Text to show a number as plain text (no thousands separator, not summed).

  • A column whose value is exactly a primary key field of a record (for example [CUST."No."] or [DOC."No."]) links to that record: it opens it in the report, and is a link in Excel and in CSV (as an =HYPERLINK(...) formula). One row can link several records. [REC."Document No."] on a document line links the line, because it is part of the line's key; to link the header, use the header's own key, such as [HDR."No."]. Records from tables without a page to open, or temporary records, aren't linked.

  • Wrap the block in an If to add rows only for some records.

Tips for rows:

  • An Add Report Row placed inside another one adds detail rows under the row the outer one just added; for example, the lines under each order.

  • On screen, each level is its own grid stacked under the one above. Selecting a row shows its detail rows in the grid below, and the inner block's Description is that grid's caption. Every grid can be filtered and sorted like any list.

  • In Excel, each group of detail rows has its own bold header row with its own column captions, indented one column under its parent row, and the group can be collapsed. In CSV the levels are flattened into one line per detail row.

  • Each level gets its rows from one Add Report Row block, and a report has at most five levels.

Nested report row examples:

  • Quick Report 'Open documents'
      └─ If FindSet() CUST in Customer (balance over 2000)
          └─ If FindSet() DOC in Sales Header (open documents of [CUST."No."])
                └─ Add Report Row    columns: Customer = [CUST."No."], Document = [DOC."No."], Date = [DOC."Order Date"]

  • Quick Report 'Open Orders'
      └─ If FindSet() HDR in Sales Header
          └─ Add Report Row          columns: Order No. = [HDR."No."], Customer = [HDR."Sell-to Customer Name"]
                └─ If FindSet() LINE in Sales Line (lines of [HDR."No."])
                    └─ Add Report Row  'Lines'   columns: Item No. = [LINE."No."], Quantity = [LINE.Quantity]

Raise Error

The Raise Error operation halts execution immediately and displays an error message to the user.  All pending modifications are rolled back.  Currently in scope variables and entities can be referenced to include specific details in the error message, for example: 'Cannot modify posted document ' + [REC."No."] + '.'.

How does script processing work?

Script blocks are executed in order from top to bottom.  Operations are arranged in a hierarchy, and child operations only run if their parent operation succeeds or loops.  SalesPad Scripting manages entity scope to prevent naming conflicts and ensure predictable behavior.

In general, variables are available to sibling operations and child blocks, while loaded records are only accessible to child blocks.  Preceding blocks do not have access to entities and variables that are loaded and set by later blocks.  Loop entities are only available for their loop iteration; when Load Entities is looping through records like sales lines, each line is only available during its loop, and it is no longer available in later loops.  Parent entities, including the source entity (REC), remain accessible through nested loops.  REC is always in scope for the entire script.

How do I build a script block tree?

You can drag operations from the palette onto the canvas, drag and drop blocks on the canvas, and make changes via the Details tab.

  • Add a block: drag an operation from the palette onto the canvas.  A drop slot lights up only where the drop is valid.  Drop it between blocks to place it at that point, or inside a block to make it a child of that block.  You can also click an operation in the palette to add it after the selected block or at the end of the script.

  • Move a block: drag it by its header. A block always moves together with everything inside it, and dragging any part of an If / Else If / Else moves the whole chain. From the keyboard, Alt+↑ / Alt+↓ moves the selected block up or down, and Tab indents it into the block above while Shift+Tab outdents it out of its parent.

  • Delete a block: press Del, use the Delete button in Details, or drag the block back onto the palette.

  • Duplicate a block: press Ctrl+D or use the Duplicate button in Details.

  • Select several blocks: Shift+Click selects a run of sibling blocks, which can then be dragged, moved, indented, duplicated, or deleted together.

  • Some blocks can't hold children (for example, Raise Error and Call Helper Script), so nothing can be dropped inside them.

Selecting a block shows its settings in Details:

  • Operation dropdown at the top: change it to turn the block into a different operation; fields that don't apply are cleared, and Ctrl+Z can restore them.

  • Description, then the fields for that operation: for example, Entity name, Table, and Filter for a load; Target entity, Field, and Value for a Set Field.

  • In scope here: chips listing the entities and variables available at that block's position in the tree.

  • Any errors found for that block by Validate or Save.

How do I use the filter editor?

Expression, condition, message, and filter fields use a rich Monaco editor with syntax highlighting and IntelliSense autocomplete.  It grows as you type; click Expand to edit a long WHERE() clause in a large overlay, and hit Esc to close it.

Filters use Business Central's standard WHERE() clause format with the following structure: WHERE("Field Name"=FILTER(value), "Another Field"=FILTER(value)).  Field references in filters are resolved at runtime to the actual field value, and comparison operators can be used within filters (=, <>, >, <, >=, <=).  

  • WHERE("No."=FILTER(10000))                          ← Item number is 10000

  • WHERE("Quantity"=FILTER(>10))                      ← Quantity is greater than 10

  • WHERE("Status"=FILTER(<>Posted))                ← Status is not Posted

  • WHERE("Unit Price"=FILTER(>=100))                ← Unit Price is greater than or equal to 100

Comma-separated fields use AND logic while pipe-separated fields use OR logic; within a field, ampersands use AND logic for conditions.  Ranges use “..”.

  • WHERE("No."=FILTER(10000|20000))               ← Item number is 10000 or 20000

  • WHERE("No."=FILTER(10000|20000|30000))    ← Item number is any of these options

  • WHERE("No."=FILTER(10000..20000))              ← Item number is between 10000 and 20000, inclusive

  • WHERE("No."=FILTER(10000), "Location Code"=FILTER(<>''))    ← Item number is 10000 and location code is not blank

  • WHERE("No."=FILTER(10000), "Location Code"=FILTER(<>A&<>B))    ← Item number is 10000 and location code is not A and not B

A [entity."Field Name"] reference in a filter is replaced with the field's value in quotes. A quote in the value is doubled automatically, so a name like O'Brien filters correctly, and a [ in the value is never read as another reference.

  • WHERE("Document No."=FILTER([REC."No."]))    ← Order’s doc number matches this record’s doc number

  • WHERE("Document No."=FILTER([REC."No."]), "Document Type"=FILTER([REC."Document Type"]))    ← Order’s doc number and type match this record

Wildcards include * (any characters), ? (single character), and @ (case-insensitive matching).

  • WHERE("No."=FILTER(*89))                  ← Item number ends with '89'

  • WHERE("No."=FILTER(100??))              ← Item number starts with '100' plus 2 characters

  • WHERE("Name"=FILTER(@*Test*))       ← Name contains 'test' (case-insensitive)

Do not use single quotes around filter values unless you want to match them literally.

  • WHERE("Name"=FILTER(@*Test*))       ← Case-insensitive wildcard match for any names containing “test”

  • WHERE("No."=FILTER('10000|20000'))  ← Matches the literal string '10000|20000' (pipe included)

  • WHERE("Name"=FILTER('@*Test*'))      ← Same as unquoted (works either way for wildcards)

By default, a load reads records in primary key order.  To read them in another order, use SORTING(...) and optionally ORDER(Descending) before the WHERE(...).  The default is ORDER(Ascending), so ORDER can be omitted if the sort field should be ascending.  You can sort on any field, including FlowFields, but sorting on fields outside a table key can be slow on large tables.

  • SORTING("Due Date") ORDER(Descending) WHERE("Document Type"=FILTER(Order))

Functions such as System.Today(), UserSecurityId(), and MAX() can be written inside a filter value, and their results are put into the filter in quotes, like a field reference.  Only the call itself is worked out, so ..System.Today()-30 does not subtract 30 days; set a variable first and filter on it instead.

Autocomplete can suggest entity and variable names that are in scope, field names for entities, and keywords and filter templates.  Use Ctrl+Space to open autocomplete, use Tab to accept the suggestion, and use Esc to close autocomplete.  Autocomplete also triggers automatically when you type . or [.  In an empty filter, autocomplete offers SORTING, ORDER, and WHERE, and inside FILTER() it lists the filter operators with their meanings.

What keyboard shortcuts are available?

The Script Designer provides a variety of shortcuts, making it simple to add and move blocks, duplicate and delete, undo and redo, and jump between blocks with validation problems.  Movement is also made easy: to pan, drag the empty canvas, middle-drag anywhere, or scroll with the mouse wheel.  Ctrl+mouse wheel zooms, or you can use the −, %, +, and Fit controls in the canvas's bottom-right corner. Click the % to reset to 100%.  

Key

Action

Del

Delete the selected block(s)

Ctrl+D

Duplicate the selected block(s)

Alt+↑ / Alt+↓

Move the selected block(s) up / down

Tab / Shift+Tab

Indent into the block above / outdent out of the parent; in a Details field, move to the next / previous field

Ctrl+Z / Ctrl+Y

Undo / redo

Ctrl+S

Save

F8 / Shift+F8

Go to the next / previous block with a problem

Esc

Clear the selection

Shift+Click

Select a run of sibling blocks

 

What is the difference between validating and saving?

Validate checks the script without saving it, while Save (or Ctrl+S) validates and then saves the whole tree.  Validating marks problems on their blocks; press F8 / Shift+F8 to jump to the next / previous one.  Designer changes are not saved until you click Save.  The toolbar shows “Unsaved” until then, and closing the page asks before discarding unsaved changes.  Reload Operations discards unsaved changes and reloads the saved operations.  The testing and Execute Script actions run the last saved version, so save first to test your latest changes.

When are scripts read-only?

Once a script has been released, it is made read-only; set the Status back to Draft to make changes.  Draft scripts with unsaved designer changes can’t be released until you save or discard them.  All scripts are read-only in a production environment that does not have an active license with Cavallo.  

How do I create a helper script?

Create a new script and set its Script Type to Helper Script.  A new Parameters section appears in the Script Designer; add parameters for information that the calling scripts will send to the helper script, then build the script blocks to process those parameters.  In the calling script, add a Call Helper Script block, select this helper script, and bind values for its parameters.

Parameters can be entities, like sales orders and sales lines, or they can be variables like numbers and text data.  They are passed by reference, so the helper script can make changes to those inputs and the calling script can use those updates.  Parameters can be added, removed, or changed while the helper is a Draft; any calling script whose bindings no longer match is listed in a banner on the helper, and the helper can't be released again until every caller matches.

Any type of script can call a helper script, including other helper scripts.  When a script calls a helper script, all logic in the helper script is executed before the processing returns to the calling script (i.e. SalesPad Scripting does not currently support multi-threading).

To call a helper script:

  1. Drag the Call Helper Script operation from the palette (Integration group) onto the calling script's canvas, then in Details click “Choose…” to select the helper script to invoke.

  2. For each of that helper script’s parameters, the Details pane lists the Parameter name and a Pass dropdown.  In the dropdown for each parameter, select an entity or variable.  The dropdowns restrict possibilities based on the type (variable vs entity), variable type or entity source table, and what is currently in scope for this block.  Every parameter is required, and the script cannot be saved until all parameters are bound to valid values.

To view or edit the helper script itself, click the Open button in the Details pane, or double-click the Call Helper Script block.  The helper script opens in its own Script Designer page.  

Helper scripts are not assigned directly to user profiles or Entra applications, and they cannot be tested with the trace, executed, or run in the background, because they are only called by other scripts.  Circular calls are detected and blocked at runtime; to prevent infinite loops, a helper script cannot call itself directly or through a chain of other helpers.  

Calling a draft helper script from another script automatically stops with an error; they must be released first.  Helper scripts can only be released as long as all scripts that call them have bindings that match their current parameter list; otherwise, an error will list each mismatched call, and you must update their bindings to match the updated helper script parameters.  The Script Type for helper scripts cannot be changed while other scripts call them; the error will list each calling script, and you must remove their Call Helper Script blocks first.  

Problems between scripts and the helpers they call show as banners.  A helper shows one banner for each calling script whose bindings no longer match, and a released calling script shows one for each helper that isn’t released, no longer exists, or has binding issues.  Each banner has a View action that opens the script that needs attention.  Deleting a helper script that other scripts still call will ask first and name those scripts; if those calling scripts aren’t adjusted, then their Call Helper Script blocks will fail when they run.

How do I handle errors?

SalesPad Scripting distinguishes between two types of errors: those that are explicitly raised in the script by a Raise Error block, and anything else that causes an unexpected error while a script is running.  Author-intended Raise Error operations always block the save, but unexpected errors can be conditionally suppressed to prevent them from blocking the save.

If you want a script to reject bad data outright, use Raise Error and it will never be suppressed. If you want a script's own bugs or edge cases to be logged and surfaced without blocking day-to-day saves, use Suppress Errors To Banner.  This toggle is enabled per script in the General fields, and it can only be changed while the script is a draft.  Suppress Errors To Banner only changes whether the save itself is blocked; it does not disable error logging and notification behavior.

When on-save scripts or helper scripts hit an unexpected error, and Suppress Errors to Banner is turned on, then the error is logged as usual and shown as a dismissable banner, but the triggering save is not blocked; it completes normally.  

When a run script hits an unexpected error, execution simply stops at that point, regardless of Suppress Errors to Banner.  The error is logged, and shown as a dismissable banner when someone runs the script manually, and any operations that took place before the error still took effect.  But any processing that would have happened after the error does not take place.  

When a helper script hits an unexpected error, only that script’s Suppress Errors to Banner setting is consulted.  This lets you mix and match: a cautious calling script (with suppression off) can call one specific helper script that is safe to suppress (helper's suppression on); or a lenient calling script (with suppression on) can treat a more fragile helper as hard-blocking (helper's suppression off).

Calling script suppression

Helper script suppression

Error timing

Result

Off

(no helper)

Calling script

Blocks the save

On

(no helper)

Calling script

Suppressed - save completes

Off

On

Helper script

Suppressed - save completes

On

Off

Helper script

Blocks the save

(any)

(any)

Via Raise Error anywhere

Always blocks the save

 

If a helper script calls another helper script, the script that is active at the time that the error occurs is the one whose suppression setting is checked.

It is important to note that this does not guarantee atomicity; SalesPad Scripting has no nested transactions or save points of its own, so any other entity that was saved by the script before the error is not rolled back, regardless of whether the error was suppressed.  When this happens, the log entry includes a warning noting how many other records were already saved before the error, so the risk is visible after the fact.

How do I review suppressed errors?

Suppressed script errors are logged in the SalesPad Scripting execution log with Log Type = “Error”, the full error message, and any partial-write warnings for saves that happened in the script before the error occurred.  In interactable sessions, the person who triggered the save will also immediately see a dismissable banner with the error message.  

How do I extend scripting to another BC page?

Adding the Run Script action buttons to another BC page requires creating an extension, adding a dependency on SalesPad Scripting, then adding a page extension to show and run available scripts based on the page’s selected record and the current user’s assigned scripts.

  1. In your extension's app.json, add a dependency on SalesPad Scripting:

"dependencies": [

  {

    "id": "ad3f6724-4c4f-49cf-8bc8-941487f8ac11",

    "name": "SalesPad Script Manager",

    "publisher": "Cavallo",

    "version": "1.0.0.0"

  }

]

 

  1. Add a page extension for the target page (and, for a document, also add one for its lines subpage). This is the Sales Order page extension used by SalesPad Scripting:

pageextension 73522638 "CAV Expr Sales Order Refresh" extends "Sales Order"

{

    actions

    {

        addlast(processing)

        {

            action(CAVScrRunAvailableScript)

            {

                ApplicationArea = All;

                Caption = 'SalesPad Run Script';

                Image = ExecuteBatch;

                ToolTip = 'Run a SalesPad script enabled for your User Profile against this record';

                Visible = CAVScrRunScriptAvailable;

                trigger OnAction()

                var

                    AssignMgmt: Codeunit CAVScrScriptAssignMgmt;

                begin

                    AssignMgmt.RunAvailableScript(Rec);

                    CurrPage.Update(false);

                end;

            }

        }

    }

    trigger OnOpenPage()

    var

        AssignMgmt: Codeunit CAVScrScriptAssignMgmt;

        TempMaster: Record CAVScriptMaster temporary;

    begin

        AssignMgmt.GetEnabledRunScriptsForTable(Database::"Sales Header", TempMaster);

        CAVScrRunScriptAvailable := not TempMaster.IsEmpty();

    end;

    var

        CAVScrRunScriptAvailable: Boolean;

}

How it works:

  • GetEnabledRunScriptsForTable finds the released run scripts for the specified table that are assigned to the current user profile. The Run Script action button is only shown if at least one valid script is found.

  • RunAvailableScript runs the script against the record. If exactly one script is available, it runs automatically.  If several are available, the user is prompted to pick one.

    • Pass the record itself (Rec) or a RecordRef, anything else raises an error. The table number is taken from the record.

    • Call CurrPage.Update(false) afterwards so the page shows any fields the script changed.

  • Automatic refresh when an OnBeforeInsert/OnBeforeModify script changes the record is only built in for the out-of-the-box BC pages. On your own page, the user sees those changes the next time the page updates.

How do I extend scripting to another table?

Even though on-save scripts can target any source table, Business Central only runs them for tables that have an event subscriber that calls SalesPad Scripting.  Enabling on-save scripts for another table requires creating an extension, adding a dependency on SalesPad Scripting, then adding the event subscribers.  Each subscriber makes a single call to the CAVScriptPreSaveSubscriber codeunit, which returns true if a script ran and hands back the changed record.

  1. In your extension's app.json, add a dependency on SalesPad Scripting:

"dependencies": [

  {

    "id": "ad3f6724-4c4f-49cf-8bc8-941487f8ac11",

    "name": "SalesPad Script Manager",

    "publisher": "Cavallo",

    "version": "1.0.0.0"

  }

]

 

  1. Add the On Before Insert script subscriber for the target table (this example is for the Sales Header table, which ships out-of-the-box with SalesPad Scripting):

[EventSubscriber(ObjectType::Table, Database::"Sales Header", 'OnBeforeInsertEvent', '', false, false)]

local procedure SalesHeaderOnBeforeInsert(var Rec: Record "Sales Header"; RunTrigger: Boolean)

var

    PreSave: Codeunit CAVScriptPreSaveSubscriber;

    RecRef: RecordRef;

begin

    if PreSave.RunOnBeforeInsertScripts(Rec, RecRef) then

        RecRef.SetTable(Rec);

end;

  1. Add the On Before Modify script subscriber for the target table (this example is for the Sales Header table, which ships out-of-the-box with SalesPad Scripting):

[EventSubscriber(ObjectType::Table, Database::"Sales Header", 'OnBeforeModifyEvent', '', false, false)]

local procedure SalesHeaderOnBeforeModify(var Rec: Record "Sales Header"; var XREC: Record "Sales Header"; RunTrigger: Boolean)

var

    PreSave: Codeunit CAVScriptPreSaveSubscriber;

    RecRef: RecordRef;

begin

    if PreSave.RunOnBeforeModifyScripts(Rec, XREC, RecRef) then

        RecRef.SetTable(Rec);

end;

Tips for script subscriptions:

  • Do not add a subscriber for a table that already has one, or its scripts will run twice

  • Only scripts assigned to the current user profile or Entra application will run

  • On-save scripts run for every insert or modify for that table made by assigned users and extensions, which can drastically affect how long it takes for the app to save records, so keep them fast

  • For a modify, the call re-reads the stored record for XREC, because the platform’s XREC is unreliable when a record is written through a RecordRef

  • Always finish with RecRef.SetTable(Rec), because the call can’t write the changes straight into your Rec

  • Tables with no released script do not hurt record save performance because the call returns false after a single lookup

What happens if a script runs into an error?

By default, a script error blocks the save automatically.  For non-critical scripts, you can turn on "Suppress Errors To Banner"; this will log the unexpected error and show it as a banner and still allow the save to go through.  Deliberate validation rules ("Raise Error") always block, whatever the setting.

When an on-save script fails, BC rolls back everything in that save, like any other BC error.  Nothing is left half-done.

Run scripts that perform bulk operations automatically save their progress in batches so a multi-hour job doesn’t lock the database the whole time.  If it fails partway, the earlier batches stay saved, and the log shows exactly where it stopped. Design large jobs so they can safely be run again (for example, filter on records not yet processed).

Can scripts get stuck in endless loops?

No.  If a helper script ends up calling itself, directly or through another helper script, the engine detects it, stops, and logs a clear error.

How do I turn off a script quickly?

Remove its assignment, or take it out of Released status. Nothing needs to be uninstalled or redeployed.

How do I trigger scripts in workflow?

Run scripts can be triggered from outside BC, so Mission Control workflow can run these scripts automatically when documents hit specific points in workflow.  Mission Control must be set up as an Entra application in BC and assigned scripts that it can run.  Then Mission Control’s Run Script workflow action can connect to your run scripts in SalesPad Scripting.

When Mission Control is set up as an Entra application, it must be assigned the SalesPad Script Manager - Execution API (CAVScriptExecApi) permission set.  This gives Mission Control the right permissions to execute SalesPad Scripting through BC.  If this is missed, then whenever Mission Control workflow tries to trigger its scripts it will fail with a permissions error.  If this permission is added but Mission Control isn’t assigned the script it is trying to run, then it will fail with a script assignment error.

Once Mission Control has been assigned scripts, those scripts can be selected in the Run Script workflow actions.  The dropdown will only show released run scripts; quick reports can’t be triggered from workflow.

How do I import and export scripts?

Scripts can be exported as JSON files for backup, sharing, or version control, and imported into other environments.  These options can be triggered from the SalesPad Scripts list.

To export a script:

  1. Open the SalesPad Scripts list

  2. Select one or more scripts

  3. Click Export

  4. A JSON file (ScriptExport_YYYYMMDD.json) downloads automatically

To import a script:

  1. Open the SalesPad Scripts list

  2. Click Import

  3. Select the JSON file

  4. The system validates, creates the Script Master records, and rebuilds the operation tree

If a script with the same name exists, the import creates a new script and appends a version suffix.  Existing scripts are never overwritten or deleted.

Imported scripts start in Draft status.  Always review and thoroughly test scripts before releasing them.

How can I test scripts?

The Script Designer provides built-in options for incrementally testing scripts before updating a Draft script to be Released.  This helps you test script changes safely before rolling them out to production where they will affect live data.  For quick report scripts, test runs generate and show the report but never email it.

The recommended pre-release flow for run scripts is:

  1. Trace Script: do dry-run trace tests against representative records, then review the execution tree and evaluated values and make sure everything changed (or did not change) as intended

  2. Test Total Count: do a dry-run count test and review the processed record volumes and nested loop multipliers to evaluate performance

  3. Execute Script: once both prior checks pass, execute against live data on a test record and ensure all updates happen as expected.  If conditional logic is included, also execute against test records that should not be updated, or should have different updates, to make sure every situation is handled properly

  4. Release: set status to Released to make the script available to use

The recommended pre-release flow for on-save scripts is different, because these scripts run automatically when a record is saved.  Trace Script and Test Total Count are not available, so test them by saving records:

  1. Enable logging: in a sandbox, turn on Enable Logging in the global script settings so each run writes its full trace

  2. Release for a test profile: release the script and assign it to a test user profile only

  3. Test record updates: insert or modify representative test records as a user with that test profile, including records that should and should not trigger the script, and review the execution log for each save to ensure all changes occur as expected

  4. Release: once the script behaves as intended, assign it to the real profiles in production and re-disable logging if no longer needed

How can I test without changing live data?

Trace Script runs a script in trace mode against a record you select. It shows each operation in execution order with evaluated values, which is useful for stepping through complex conditional branches.  This is a dry run; it does not insert, modify, or delete database records.  The execution log shows what the script would attempt based on the database state at the start of the trace.  Trace Script can only be used for run scripts.  

Trace Script cannot reproduce a live execution flow when a later operation depends on a database change made by an earlier operation. For example, a later load or lookup will not see a record created or modified earlier in the same trace, because that change was not written to the database. Validate these scripts with Execute Script against a safe non-production record.

Run Codeunit is not executed in a trace.  Because a codeunit can do anything, including database writes or commits, the trace will not call it. The log only records that the codeunit would have run ("DRY RUN: Would run Codeunit ..."). Any changes the codeunit would make, and any errors it would raise, will not appear in the trace. Test those situations with Execute Script against a safe test record.

Use Trace Script to:

  • Verify logic before releasing a new script

  • Confirm behavior on a specific representative record

  • See which If/Elif/Else branches are taken

  • Verify that scripts resolve to the expected values

  • Debug logic that produces unexpected results

  • Catch errors early without changing data

How can I optimize performance?

Test Total Count runs the script in count-only mode.  Load operations execute and count their results, but no fields are set and no records are modified.  Test Total Count can only be used for run scripts.

Example output:

Entity Load Counts:

  lines:   45 records

  vendors: 180 total iterations (45 lines × 4 vendors per line)

  items:    45 total iterations (45 lines × 1 item per line)

Total Iterations: 225

Use Test Total Count to:

  • Understand how many records the script will touch

  • Identify multiplicative effects of nested loops

  • Validate that filters are scoped correctly

  • Estimate runtime before executing against large datasets

How can I safely test with live data?

Execute Script runs the script against a selected record in live mode. All modifications are committed to the database, and this action is not reversible through the script system.  Always execute with a safe test record, ideally in a sandbox before testing in production.

How do I move scripts from sandbox to production?

Build and test in a sandbox, export the scripts to a JSON file, and import them into production.  Imports never overwrite anything: a name clash gets a new copy with a suffix, and every imported script is flagged as a Draft, so nothing goes live until someone releases it.

How do I copy scripts from one company to another?

Scripts are stored per company, like most BC data.  To use the same script in another company, export it and import it there. This also means a new script can be rolled out to one company first.

How can I run bulk operation scripts?

From the Script Designer, in the Actions dropdown, select Execute Script and then Run In Background.  This queues the script in the Job Queue so it can run asynchronously without blocking the UI.  Use this for large datasets (thousands of records), operations that would otherwise time out in an interactive session, and scheduled or automated bulk operations.

How do I schedule recurring scripts?

From the Script Designer, in the Actions dropdown, select Execute Script and then Schedule Execution.  This creates and opens a Business Central Job Queue Entry for automated recurring execution of the script.  Scheduled scripts run without a user selecting a specific source record, so this action is only available for released run scripts and emailed quick report scripts with no set source table.  Scheduled quick reports must have Email Report enabled for every Quick Report block.  

On the Job Queue Entry card, set the desired start date/time and recurrence settings.  Once all desired configuration options are set, change the Status from On Hold to Ready to allow BC to run it.

When this action is selected for a script that already has a Job Queue Entry, that existing card will be launched instead of creating a new entry.  Deleting a scheduled script, changing its Script Type, or giving it a Source Table No. asks first and then deletes its Job Queue Entry.

How do I use Copilot with scripting?

SalesPad Scripting includes an optional Copilot AI assistant built into the Script Designer. You describe what you want to change, and Copilot proposes blocks on the canvas for you to review, apply, and save — instead of building every block by hand. You can also ask questions about the script, or about your other saved scripts.

Connect Copilot in the global script settings, then open a script and switch the right panel from Details to Copilot.

Copilot knows which blocks are selected on the canvas (shown in the Selected chip), so you can say things like "after this" or "inside this block". Copilot always reads the script as it is on the canvas, including your unsaved changes.  You can ask what the script does to see an overview of its logic in plain language.

You can ask a question or describe the changes you want to make in the text box.  Press the Enter key or click the Send button to submit.  When you ask a question, Copilot gives an answer.  When you ask for changes, Copilot looks up real table and field names, checks its proposal against the script rules, and fixes any errors before showing it to you.  If it needs more details, it asks you a question instead.

You can review Copilot’s proposal on the canvas.  Proposed changes are drawn on the canvas as a diff, and listed under Proposed changes in the Copilot tab:

  • + new blocks Copilot wants to add

  • ~ changed blocks whose fields Copilot wants to change

  • ↕ moved blocks Copilot wants to move

  • − removed blocks Copilot wants to delete, shown as ghosts

  • ★ a new Helper Script Copilot wants to create (created as Draft on Apply)

Click an entry in the list to scroll the canvas to that block. If the designer finds scope problems in the proposal (for example, a reference to an entity that isn't in scope at that point), they are listed with an “Ask Copilot to fix” button. While a proposal is open, editing, Save, and Undo are locked, and the toolbar shows “Reviewing Copilot proposal”.

You can choose to apply or discard the proposal, or make changes to it by continuing to chat with Copilot.  Copilot keeps the conversation so you never need to repeat earlier messages, and the new proposal replaces the previous one.  

When you apply changes, the proposal is applied to the designer canvas.  The script must still be saved for the changes to be officially committed.  If you undo (Ctrl+Z), the entire proposal is reverted.  Any new helper scripts are created as new Drafts, and the Call Helper Script blocks are linked to them.  If you undo the applied proposal, the helper scripts will still exist, so they should be deleted from the SalesPad Scripts list if they are not needed.

When you discard changes, the entire proposal is dropped, and the canvas reverts to its previous state.

You can start a new chat with Copilot by clicking the “New chat” button at the top of the Copilot tab.  

How do I create a new script with Copilot?

Create the script first, then open the Copilot tab and describe what the script should do.  Copilot will suggest blocks on the empty canvas for you to review, modify, apply, and save.

What can Copilot do to scripts?

Copilot can add, change, move, and remove script blocks, create new helper scripts, search and read other saved scripts, call existing helpers, and explain scripts.  Released scripts are readonly so Copilot can only answer questions and explain what it would change; set the Status to Draft in order to apply proposals.

How do I use Copilot responsibly?

Copilot uses generative AI, and AI-generated content can be wrong.  You are responsible for the scripts you release, so make sure to fully review all AI-generated content and comprehensively test scripts before using them (ideally in a sandbox environment before production).

Once scripts are released, they can change live business data and block or alter saves for every assigned user.  Copilot is a drafting aid; it does not replace your own judgement or your organization’s review and approval process for changes to business logic.

Your request, the conversation so far, the open script's blocks (including unsaved changes), any other saved scripts Copilot searches or reads, and the table and field definitions (names and types) that Copilot looks up are sent to the Azure OpenAI resource configured in settings.  That resource is covered by your organization's own Azure agreement and data-handling settings.  Do not include passwords, personal data, or other sensitive information in your requests.

Copilot can be turned off for an environment at any time on Business Central's Copilot & AI Capabilities page ("SalesPad Script Builder"). Using the Copilot tab also requires the SalesPad Script Authoring Admin (or SalesPad Script Admin - Full Access) permission set.

How can I make my scripts as performant as possible?

Keep your scripts running fast by tightly filtering loaded records, keeping on-save scripts simple and focused, and using the Script Designer’s dry run tests to gauge performance and tighten things up before releasing scripts to production.

Tips for performance: 

  • Filter tightly: load the lines for this order, not all lines.

  • Check Test Total Count before running anything large.

  • Send big jobs to the background or the Job Queue, ideally off-hours.

  • Avoid nested loops over large tables; filter the inner lookup to the specific record instead.

  • Keep on-save scripts short and focused; they run on every save for the assigned users.

  • Leave full execution logging off in production unless troubleshooting.  Errors are always logged anyway.

What happens to scripts during software updates?

Scripts are data stored in BC, not code, so they're kept when SalesPad Scripting is updated. Nothing needs to be rebuilt.  On the rare occasion that BC changes in a way that breaks scripts, errors are clearly logged and can also be emailed for fast resolution.  Cavallo highly recommends testing key scripts in a sandbox as part of your typical BC upgrade process.

Microsoft rarely renames or removes standard fields, but if a field that a script uses is changed or goes away, the script fails with a clear, logged error (and an email alert, if set up). Best practice is to re-run Trace Script on key scripts in a sandbox when testing any major BC updates, as you would test any extension.

Helpful Unhelpful

1 of 1 people found this page helpful