​Using JavaScript For Business Central Development

We can use the built-in “Control Addin Object” in AL to use JavaScript and render dynamic HTML onto a page in Business Central. In this post we will create a basic iFrame (a webpage within a Business Central page)...

File Structure


If you want to follow along, add this file structure to your new AL codebase. Create the files and leave them blank for now. We will go through the content of each file one by one.

The Control Add-in Object


Let’s first create the Control Add-in object by heading over to the Ctrl.al file. Use the code snippet tcontroladdin to create a boiler template. You can then modify it to this:



In this object, we are creating an object with a specified width and height. We are also linking the necessary scripts and stylesheets that will be used to render dynamic HTML.

The Startup Script


Recall the event “MyEvent()” from the control add-in object? Well that event is defined in the startup.js script like so:



This script runs once the control add-in object is initialized and creates an event called ‘MyEvent’ that invokes a trigger in AL on a page with that control add-in.

The Main Script


Now moving on to script.js, we create the following function MyProcedure() which we will call in our AL page:



Once the control addin is loaded into the DOM, we can access it since by its element id which is ‘controlAddin’. We can then insert HTML into it using the insertAdjacentHTML() javascript method. This will generate the HTML string inside our AL test page.

The Test Page


We will now use AL string manipulation to add HTML to your iFrame.



In this page we first add the control add-in object we created to the page. Then we call the procedure defined in script.js which will take in the HTML string that we will create.

To create the HTML string, define a procedure on line 17. This procedure returns the HTML string which in turn becomes the input to the MyProcedure function we created in the script.js.

You can be as creative as you want if you know HTML. All you need to do is create the HTML as a string like in the example shown.

Styling the HTML


To make your dynamically rendered HTML look the way you want, you can use CSS in the styles.css file. Here is a basic style to make a white text box.

Final Result


You can test to see if this works by opening up your test page after deploying to you cloud sandbox ordocker instance.

Use Cases


The control-addin object can be very useful when integrating an external API since it allows developers to use JavaScript. For example, you can create a form from a RESTful payment service API and embed that to your Business Central page.

This also gives developers more flexibility when enhancing UI/UX since it doesn’t limit us to the built-in objects in AL anymore.

References


1. https://docs.microsoft.com/en-us/learn/modules/build-control-add-ins/
2. https://www.youtube.com/watch?v=8TurwMAq54c&t=105s