ControlAddIns for Custom Controls
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② When every section has a ✓, tap Complete lesson.
0 of 11 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Advanced AL Programming: Mastering ControlAddIns
Introduction: Bridging the Gap Between AL and the Browser
In the world of Business Central development, the AL language serves as the backbone for business logic, data manipulation, and page structure. However, there are times when the standard set of AL controls—fields, repeaters, and actions—simply isn't enough to meet specific user interface requirements. Perhaps you need to display a complex interactive chart, integrate a signature capture pad, or embed a real-time map interface that pulls data directly from your database. This is where ControlAddIns come into play.
ControlAddIns act as the bridge between the server-side AL environment and the client-side browser environment. They allow you to write custom JavaScript, CSS, and HTML to create a unique UI component that lives within the Business Central web client. By utilizing this technology, you move beyond the limitations of standard page objects and enter the realm of true custom application development. Understanding how to build, deploy, and interact with these components is essential for developers tasked with creating high-end, user-friendly business solutions.
This lesson explores the full lifecycle of a ControlAddIn, from the initial architectural design and manifest configuration to the asynchronous communication patterns required to pass data back and forth between AL and JavaScript. We will examine how to ensure your custom controls remain performant, secure, and compatible with the ever-evolving Business Central web client.
Not read yet
Understanding the Architecture of a ControlAddIn
At its core, a ControlAddIn is a combination of two distinct layers: the AL definition (the interface) and the client-side resource bundle (JavaScript, CSS, and HTML). When a user opens a page containing a ControlAddIn, the Business Central server sends the definition to the browser, which then fetches the associated web resources. Once loaded, the two environments exist in parallel, communicating via an event-driven mechanism.
The Manifest File (script.json)
The script.json file is the blueprint for your ControlAddIn. It tells the Business Central platform which files to load and in what order. A typical manifest includes references to your JavaScript files, CSS stylesheets, and any third-party libraries (like Chart.js or D3.js) that your control might depend on.
The AL Interface
In AL, you define the ControlAddIn using an object of the same name. This object acts as a proxy for your JavaScript code. You declare procedures that your AL code can call (which trigger functions in JavaScript) and events that your JavaScript code can fire (which are handled by AL code). This separation ensures that the compiler knows exactly what data types are expected on both sides of the communication bridge.
Callout: The Communication Bridge It is helpful to think of the ControlAddIn as a miniature API. The AL code is the client, and the JavaScript code is the server. Because the browser and the server operate in different memory spaces, you cannot pass complex objects or references directly. You must serialize data—usually as JSON strings—to pass information across the bridge, and then deserialize it on the other side.
Not read yet
Step-by-Step: Creating Your First ControlAddIn
To build a custom control, you must follow a structured approach. Let’s walk through the creation of a simple "Message Display" control that allows the user to trigger a toast notification from AL code.
Step 1: Define the AL Object
Create a new file named MessageDisplay.ControlAddin.al. This file defines the interface that the rest of your AL code will see.
controladdin MessageDisplay
{
Scripts = 'js/message.js';
StyleSheets = 'css/message.css';
StartupScript = 'js/startup.js';
// This procedure is called from AL to trigger the UI
procedure ShowMessage(Message: Text);
// This event is fired from JavaScript to notify AL
event OnMessageClosed();
}
Step 2: Implement the JavaScript Logic
In your js/message.js file, you need to implement the function that AL calls. You must expose this function to the global scope or attach it to the Microsoft.Dynamics.NAV.InvokeExtensibilityMethod context.
// js/message.js
function ShowMessage(message) {
const container = document.getElementById('controlAddIn');
const toast = document.createElement('div');
toast.innerText = message;
toast.className = 'toast-style';
container.appendChild(toast);
// After 3 seconds, remove the message and tell AL it's done
setTimeout(() => {
container.removeChild(toast);
Microsoft.Dynamics.NAV.InvokeExtensibilityMethod('OnMessageClosed', []);
}, 3000);
}
Step 3: Integrate into an AL Page
Now, use the control on a page object. You treat it just like any other field, but you use the usercontrol keyword.
page 50100 MyCustomPage
{
layout
{
area(Content)
{
usercontrol(MsgControl; MessageDisplay)
{
ApplicationArea = All;
// Handle the event from JS
trigger OnMessageClosed()
begin
Message('The message was closed in the browser.');
end;
}
}
}
actions
{
area(Processing)
{
action(TriggerMsg)
{
trigger OnAction()
begin
CurrPage.MsgControl.ShowMessage('Hello from AL!');
end;
}
}
}
}
Not read yet
Advanced Communication: Passing Data Safely
One of the most common requirements for custom controls is passing complex data, such as a list of Sales Orders or Customer records, into a JavaScript visualizer. Since AL is strongly typed and JavaScript is dynamically typed, you must be careful with how you serialize this data.
Using JSON for Complex Data
Never try to pass a Record object directly to a ControlAddIn. Instead, use the JsonToken, JsonObject, and JsonArray types in AL to build a structured payload.
procedure SendDataToJS(CustNo: Code[20])
var
JObj: JsonObject;
JArr: JsonArray;
Cust: Record Customer;
begin
if Cust.Get(CustNo) then begin
JObj.Add('Name', Cust.Name);
JObj.Add('City', Cust.City);
// Serialize to string
CurrPage.MyControl.LoadData(Format(JObj));
end;
end;
On the JavaScript side, use JSON.parse() to convert the string back into a usable object:
function LoadData(jsonString) {
const data = JSON.parse(jsonString);
console.log("Customer Name: " + data.Name);
// Render your UI using the data object
}
Note: Always validate your JSON strings before parsing them in JavaScript. Malformed JSON will cause the ControlAddIn to crash, leaving the user with a blank screen or a script error in the browser console.
Not read yet
Best Practices and Industry Standards
Working with ControlAddIns requires a disciplined approach to ensure your application remains maintainable and performant. Because you are essentially writing a mini-web application inside Business Central, you are responsible for the entire lifecycle of that application.
Performance Optimization
- Minimize Resource Size: Keep your JavaScript and CSS files as small as possible. If you are using large libraries like D3, consider using a minified version.
- Lazy Loading: If your control is complex, do not initialize the heavy lifting until the
OnControlAddInReadyevent has fired. This ensures the Business Central page loads quickly before the control starts its heavy processing. - Avoid Global Namespace Pollution: Wrap your JavaScript code in an IIFE (Immediately Invoked Function Expression) to prevent variable collisions with other extensions.
Security Considerations
- Sanitize Inputs: Never take a string from AL and inject it directly into the DOM using
.innerHTML. This is a classic Cross-Site Scripting (XSS) vulnerability. Always use.textContentorinnerTextto set data values. - Content Security Policy (CSP): Be aware that Business Central enforces a strict CSP. You cannot load scripts from external CDNs (like Google Fonts or external jQuery hosts). All your dependencies must be included as part of your extension package.
Maintainability
- Modularize Your Code: Split your JavaScript into multiple files based on functionality. Use a clear naming convention for your procedures and events.
- Error Handling: Always wrap your JavaScript logic in
try-catchblocks. If an error occurs, consider adding a mechanism to report that error back to AL via anOnErrorevent so you can log it in the Business Central Telemetry.
Not read yet
Comparison of ControlAddIn Properties
When defining your ControlAddIn object, several properties dictate how the control behaves within the browser. Understanding these is key to a smooth user experience.
| Property | Description | Common Use Case |
|---|---|---|
VerticalShrink |
Allows the control to shrink if the page space is limited. | Simple status indicators. |
VerticalStretch |
Allows the control to expand to fill available space. | Interactive maps or charts. |
HorizontalShrink |
Allows width to adjust based on content. | Small input widgets. |
HorizontalStretch |
Allows width to fill the container. | Large data tables or dashboards. |
RequestedHeight |
The initial height in pixels. | Providing a consistent starting size. |
RequestedWidth |
The initial width in pixels. | Ensuring the UI doesn't look cramped initially. |
Warning: Be very careful with
HorizontalStretchandVerticalStretch. If you set these totruewithout proper CSS styling in your control, the control may cause the entire page to overflow, leading to ugly double-scrollbars on the page.
Not read yet
Common Pitfalls and How to Avoid Them
Even experienced developers encounter issues when dealing with the boundary between AL and JavaScript. Here are the most frequent problems and the strategies to mitigate them.
1. The "Control Not Ready" Race Condition
A frequent error occurs when the AL code tries to call a JavaScript function before the browser has finished loading the script files.
- The Fix: Implement an
OnControlAddInReadyevent in your AL definition. Your AL code should wait for this event to fire before attempting to send any data to the control.
2. Failing to Clean Up
When a page closes, the JavaScript objects created in the browser stay in memory if they are attached to the window object. If the user navigates back and forth to the page frequently, this can lead to a memory leak.
- The Fix: Always nullify your variables and remove event listeners when your control is destroyed or when the page is closed.
3. Ignoring Browser Compatibility
Business Central is accessed via various browsers (Chrome, Edge, Safari). While modern browsers are generally consistent, minor differences in how they handle CSS Flexbox or Grid can lead to layout issues.
- The Fix: Use CSS autoprefixers and test your control in both Chrome and Edge. Avoid using experimental JavaScript features that aren't fully supported in the minimum browser versions specified by Microsoft.
4. Excessive Communication
Calling InvokeExtensibilityMethod thousands of times per second (e.g., in a scroll event) will degrade performance significantly.
- The Fix: Use "throttling" or "debouncing" in your JavaScript code. This ensures that you only send data back to AL at a reasonable frequency (e.g., every 200 milliseconds).
Not read yet
Debugging Techniques
Debugging a ControlAddIn is significantly different from debugging standard AL code. Since your logic lives in the browser, you must use the browser's native developer tools.
Using the Browser Console
Press F12 in the Business Central web client to open the Developer Tools. Go to the "Console" tab. Any console.log() statements you place in your JavaScript will appear here. This is your primary way to inspect the data flowing into your control.
Setting Breakpoints
You can also use the "Sources" tab to find your specific JavaScript file within the Extensions folder structure. You can set breakpoints directly in the browser to pause execution and inspect the state of your variables at runtime.
Debugging the AL Side
While you can't step directly from AL into JavaScript, you can use the AL Debugger to verify that the data being sent to the InvokeExtensibilityMethod is correct. If the data is correct in AL but wrong in JS, you know the issue is in your serialization or deserialization logic.
Not read yet
Practical Example: Implementing a Signature Pad
Let's look at a more complex, real-world scenario: capturing a user's signature. This requires a canvas element, mouse/touch event listeners, and a way to export the image data back to AL.
AL Definition (Excerpt)
controladdin SignaturePad
{
Scripts = 'js/signature.js';
procedure Clear();
procedure GetSignature(): Text; // Returns base64 string
event OnSigned();
}
JavaScript Implementation (Excerpt)
// js/signature.js
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
// ... setup mouse events to draw on canvas ...
function GetSignature() {
return canvas.toDataURL('image/png');
}
function Clear() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
AL Page Usage
trigger OnAction()
var
Base64String: Text;
begin
Base64String := CurrPage.SigPad.GetSignature();
// Save Base64String to a BLOB field in a table
end;
This pattern is highly effective for any scenario where the user needs to interact with the UI in a non-standard way. By using the canvas as the interface and the Base64 string as the data carrier, you effectively bypass the limitations of standard AL forms.
Not read yet
Expanding Your Horizons: Beyond Basic Controls
Once you are comfortable with basic ControlAddIns, you can start exploring more advanced patterns.
Integrating External Libraries
You can include entire libraries if they are self-contained. For example, adding a charting library like Chart.js allows you to create highly interactive, animated dashboards that update in real-time as the user navigates through records. Remember: you must include the full source code of the library within your extension's project folder.
Responsive Design
Because Business Central is responsive, your ControlAddIn should be too. Use CSS Media Queries to change the layout of your control based on the width of the container. If the user is on a mobile device, your control might need to switch from a complex grid view to a simplified list view to remain usable.
Theming
Business Central has a dark mode and a light mode. Your ControlAddIn should respect these settings. You can detect the current theme by checking the CSS classes applied to the body element or by using CSS variables that Business Central exposes. Designing your CSS to use var(--color-background) and var(--color-text) will ensure your control looks like a native part of the platform.
Not read yet
Key Takeaways for the Advanced Developer
- Strict Separation of Concerns: Keep your AL logic focused on data retrieval and business rules, and your JavaScript logic focused on UI rendering and user interaction. Never mix these responsibilities.
- Asynchronous Communication is Mandatory: Understand that all communication between AL and JavaScript is asynchronous. Design your code to handle callbacks and events rather than assuming immediate execution.
- Data Serialization: Use JSON as your universal language for passing data between the server and the client. Always validate and sanitize this data to prevent security vulnerabilities.
- Performance is a Priority: Treat your custom control as a web application. Minimize file sizes, debounce event listeners, and avoid memory leaks by cleaning up your DOM elements and event handlers.
- Leverage Browser Tools: Master the browser's Developer Tools (
F12). This is the only way to effectively debug the client-side logic of your control. - Respect the Platform: Use CSS variables to ensure your control respects the user's theme (light/dark mode) and follows the design language of the Business Central web client.
- Documentation and Testing: Because ControlAddIns are inherently more complex to maintain, document your JavaScript code thoroughly and implement automated tests for your AL procedures to ensure they handle the interaction with the control correctly.
By following these principles, you will be able to create custom UI components that not only solve specific business problems but also feel like a seamless, high-quality extension of the Business Central ecosystem. Whether you are building a simple input widget or a complex data visualization tool, the ControlAddIn is your most powerful asset for delivering a top-tier user experience.
Not read yet
Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.
Spend your points to unlock exam-style practice questions
Spend points to unlock MB-820 exam-style practice questions.
Practice for MB-820