Extend Model-driven Apps With JavaScript Scripts

Extend Model-driven Apps With JavaScript Scripts
HTML code snippet

Low-code solutions provide businesses with an amazing set of tools to take the process from gathering requirements to deploying the production solution and increase the speed-to-market. In theory, it sounds great.

It saves time for developers, makes it easier for new features and changes to be added throughout the project, and, most importantly, allows testing products without requiring large investments into the initial development phase.

Developer dealing with constantly changing requirements.
It often happens when the requirements for a project change later in the stages. Despite following an agile development approach, working in two-week sprints, and asking the business people for continuous feedback, core features can and will change later down the road. The ability to adapt, and improve existing solutions in a matter of days, as opposed to weeks with lower-level languages, improves the business case of going with low-code.

The Problem With Low-Code Solutions

The biggest downside, however, is the lack of customizations that your business case might require. Model-driven apps are a great example of a low-code tool; in a matter of minutes, an application can be created based on the data model, with a view and a form.

But what happens when you need to add some functionality that is not currently possible with out-of-the-box features? You create the custom scripts that you then add to the website.

Preparing Development Environment

Each developer has their preference for where the code should be written. Some upload the initial script and only modify it through xrmtoolbox, the classic interface, or even notepad. Others, including me, prefer to use an integrated development environment (IDE) to create and update scripts for your solutions.

Visual Studio Code

You can download Visual Studio Code here, the IDE I use, but I encourage you to look into all the available tools and decide which fits your style best. This should improve your experience with code formatting, plugins, and more.

Now, you are ready to write your first script. While no previous knowledge of JavaScript is necessary to follow this article, you should look into JavaScript later to write clean and efficient code.

Creating Your First Script

First, it is important to understand the example I will use in this post. The idea is that we need to validate that the user has filled out all of the fields properly within a form. There are better, out-of-the-box (business rule) ways to approach this problem, but it should provide you with an understanding of using model-driven app fields within a custom script.

For the application, we will use the 'Salary Increase' App we made in one of the earlier articles in this blog. It has a field called 'New Salary', and we would like to display a popup to the user who is validating that the Salary is not over the limit.

Let's create a new file and call it 'validateSalaryAmount.js', where we will store the code, open it in visual studio code or the editor of your choice, and start it off by creating a new function that takes in a parameter called 'formContext'.

The logical name for a column in PowerApps studio

Now, we need to access the value currently provided in the salary field and ensure that the field is not empty. To do this, we need to find the logical name of the field we want to access. There are multiple ways to find it, but for now, let's go to PowerApps studio, open the table, find the column, and copy the theological name.

function validateSalary(formContext) {
    const newSalary = formContext.getAttribute("sain_newsalary").getValue()
}

Now, we need to return a popup to the user with one of these scenarios:

  • New Salary is empty
  • New Salary is over 40'000
  • New Salary is below 40'000

For the first one, we need to check that the value of the attribute we got is null.

const MAX_ALLOWED_SALARY = 40000

function validateSalary(formContext) {
    const newSalary = formContext.getAttribute("sain_newsalary").getValue()

    if (newSalary === null) 
        return Xrm.Navigation.openAlertDialog("The 'New Salary' field is empty! Please fill it out and try again.")

    if (newSalary > MAX_ALLOWED_SALARY) 
        return Xrm.Navigation.openAlertDialog("The 'New Salary' is too high. Please review the guidelines.")

    if (newSalary <= MAX_ALLOWED_SALARY) 
        return Xrm.Navigation.openAlertDialog("The salary meets the criteria!")
}

Here we are using the Xrm.Navigation.openAlertDialog function to return a message to the user who ran the code - pretty simple. Once we have the code ready to go, we need to add it to our website.

Integrating Our Script With The Model-Driven App

First, we will need to upload the script as a web resource. It is much easier than it sounds; all you need to do is to head over to PowerApps Studio, navigate to your solution, and under '+New' choose 'Web resource'

Create a new web resource in PowerApps Studio
Next, we need to fill out some details. Upload the script file, and choose the display name and the type of the file.
Add the necessary data to the web resource

Once it is ready, we will go to our application and add a new button to the command bar. For that, open your application in the editor mode, under App, find your table, which in our case is 'Increase Request' and click 'Edit command bar'; that will open a new window.

Edit the command bar of a Dataverse table.

Then, you will need to specify where the button should be visible. To keep it simple, let's choose the 'Main form', which will let us run the script when we have opened a new form or existing record. Now, select '+ New'  - 'Command', and choose JavaScript file.

You will notice that you can also choose Power Fx, a powerful language you can use to develop some customizations for the website, but it will be limited compared to what JavaScript can achieve.

Next, choose a label and an icon for the button, and under the library, click on 'Add Library', where you will search for the Validate Salary Amount web resource we created. Then, click 'Add' and provide the function name that should be called. This will be the same name as you called your function in your code. In our case, that is 'validateSalary'.

Lastly, we need to pass in the parameter formContext, which lets our script access information in our form context. To do this, click on '+ Add parameter' and change the type to 'Primary Control'.

Pass Primary Control to the JavaScript function.

That is it! We have now created the script, added it to our solution, created a new command and passed the formContext to it. All left to do is 'Save and Publish' and test the script.

Making Sure the Script Is Working

A salary of 55'000 is more than the allowed value.
The Salary of 32'000 meets the criteria. 
An empty field is not allowed.

That is it! Of course, for such a simple validation, you should be looking to use a business rule or a simple Power Fx function. Still, I hope it helped you understand the process of creating and extending the out-of-the-box functionality with your custom code snippets. Best of luck!