© Sanjaya Yapa  2019
Sanjaya YapaCustomizing Dynamics 365https://doi.org/10.1007/978-1-4842-4379-4_3

3. Out-of-the-Box Customizations

Sanjaya Yapa1 
(1)
Kandy, Sri Lanka
 

In this chapter, you will start developing the SBMA membership application. In this initial phase of development, the primary focus will be on out-of-the-box customizations. In Chapter 2, we discussed the details of how to create the base solution, and in this chapter, we will create basic customizations as solution patches and showcase the steps to add the solution to source control and to the target environment.

Form Customizations

To get started with form customizations, you will first create the solution patch that will include the form customizations. By using solution patching, you can include the forms that you are going to modify in the patch without bothering to have all the other components in the solution. This section will cover how to add fields and custom entities to the system and how to arrange the main forms of those entities.

When creating the solution patch, navigate to Settings and select Solutions. In the solutions grid, select the SBMA solution and click Clone a Patch in the grid toolbar, as illustrated in Figure 3-1.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig1_HTML.jpg
Figure 3-1

Cloning the base solution

Note that the version number has increased, and the base solution will not allow any modifications. All modifications should go into solution patches hereafter until you clone the solution. Click the Save button, and the solution patch will be created. See Figure 3-2.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig2_HTML.jpg
Figure 3-2

Solution patch versioning

Now you can add the components. Remember, you will be modifying only the main form and adding new fields as required. So, you have to add the entity and the main form only. This is the same as adding existing items to the base solution. The only difference is that you are selecting the required components only.

After selecting the item in the Missing Required Components window, select “No, do not include the required components.” You already did this when you first imported the base solution. As shown in Figure 3-3, the solution patch contains all the required components.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig3_HTML.jpg
Figure 3-3

Solution patch with entities

Expand the entity and the forms; you will see that only the main form is included in the solution patch (see Figure 3-4).
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig4_HTML.jpg
Figure 3-4

Solution patch containing only the main form

To begin with the customizations, you will start with the Member form. It is always good to list the changes that you are going to do to the form.
  1. 1.

    Identify the fields that are required. Member is a custom entity, and it already has some fields out of the box. It is always good to use these as much as possible. Since the form is going to be modified to meet SBMA’s requirements, it is a best practice to create a new main form so that the default, out-of-the-box form remains as it is.

     
  2. 2.

    If any additional fields are required for the final application, create those additional fields.

     
  3. 3.

    Arrange the interface by adding the new fields and removing any unnecessary fields and sections.

     

The default Member form is a huge form; you do not require all the sections on the form for the application, so you can remove the sections not necessary for the application. For instance, you can remove Marketing, Contact References, etc., as per the SBMA application requirements. You can simply select the section and hit Delete on the keyboard or click the Remove button on the ribbon.

To arrange the form properly, double-click the Summary tab, and on the Properties tab, click the desired layout; then click OK. See Figure 3-5.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig5_HTML.jpg
Figure 3-5

Form tab formatting

Note

When removing sections, keep in mind that the components in that section will also be removed. If that happens, then you will have to add the items again. For instance, by default on this form there are three columns, and if you change the formatting to have two columns, then you will lose the components in the third column. The trick is that you can move the items in column 3 to column 1 and change the formatting to One Column. You also have Undo and Redo options. The nice thing about the form editing is that while editing the form, you can preview the changes. See Figure 3-6.

../images/471991_1_En_3_Chapter/471991_1_En_3_Fig6_HTML.jpg
Figure 3-6

Form editor ribbon: Preview, Undo, and Redo buttons

To remove an unnecessary field, you can select a field and click the Remove button on the ribbon. To add new fields to the form, drag and drop the field from the Field Explorer to the desired location on the form. See Figure 3-7.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig7_HTML.jpg
Figure 3-7

Form customizations: adding and removing fields

As shown in Figure 3-8, forms can be edited with the new WSYWIG Form Editor, which is in preview at the time of writing the book. You can sign into PowerApps, expand Data in the left pane, and select Entities. Select the entity, and on the Forms tab you can select the form and edit it. You can find more information at https://powerapps.microsoft.com/en-us/blog/introducing-the-new-wysiwyg-model-driven-form-designer-public-preview/ .
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig8_HTML.jpg
Figure 3-8

Form Editor(preview)

To add a new field to the Member entity, just click the New Field button in the Field Explorer pane. This will open the form to add a new field. Or you can go back to the solution and select the fields from the usual left pane under the Fields menu of the Member entity. As shown in Figure 3-9, a new option set field can be added to the entity.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig9_HTML.jpg
Figure 3-9

Adding a new option set field to the Member form

After making all these changes, you can save the form and click Publish Customizations, which will apply the changes to the form, as shown in Figure 3-10.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig10_HTML.jpg
Figure 3-10

Member form in the Unified Interface

Like with the Member form, add the fields to the other entities and place them on the forms as required. The event form fields are laid out as shown in Figure 3-11. For instance, the following are the fields that should be used to capture the event-related information:
  • Event Code: This field is used to identify the events and is a unique code. As you can see, the field is set to Business Required, and the length of the field is 10 characters. All these properties can be set when you create the field.

  • Name: This is also set to Business Required, and it is an out-of-the-box field.

  • Event Status: This is an option set that defines the workflow of the event from start to completion or cancellation.

  • Event Budget: This is a currency type field for allocating the funds for the event.

  • Start Date and End Date: These are date-time fields that define the event’s start date and end dates. When defining date-time fields, you can choose not to show the time field. But in this context, the time part is required. This is set to Business Required because for a given event, there must be a start date and an end date.

  • Registration Start and End Date: Like with the event start and end dates, you can define the start and end dates for event registrations. Again, these fields also require a time part.

  • Event Capacity: This defines the number of registrations allowed in the event, which is usually a whole number. This is not always required because there could be events with unlimited registrations such as fundraising events.

../images/471991_1_En_3_Chapter/471991_1_En_3_Fig11_HTML.jpg
Figure 3-11

Event form

After completing all these customizations, it is good to add the changes to source control. So, as explained in Chapter 2, update the solution name in SPKL.json with the unique name of the solution patch (SBMASolution_Patch_4ce06dde). Then use the SPKL unpack.bat file to extract and check in the solution patch to source control, and use the SPKL pack+import.bat tool to package it and import it to the target environment.

In the next section, the book will elaborate on how to set autonumbering for the entities.

Autonumbering Option

Autonumbering was one of the biggest pain points until the recent past because not all entities supported autonumbering option. Developers had to invent ways of implementing autonumbering for custom entities. But, ever since the version 9.0 release, you can create autonumbering for any entity. At the time of writing this book, there is no interface to configure the autonumbering, but in XrmToolBox, there is a plugin called Auto Number Manager that can be used to configure the autonumbering for any entity of the solution.

There are several autonumber formats supported by this feature. You can find more details about autonumbering at https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/create-auto-number-attributes .

Since this is going to involve more customizations, you can create another solution patch and include the entities that require autonumbering. Similar to the previous patch you created, include only the entity and the main form, and click “No, do not include required components.” For the examples given here, we will be using the Member and Event entities.

First, let’s establish a connection from XrmToolBox to the Dynamics 365 instance. Open the toolbox and click the Connect button on the toolbar, as illustrated Figure 3-12. Also, you will have to provide the instance URL and on the next screen the username and the password.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig12_HTML.jpg
Figure 3-12

Connect to the Dynamics 365 instance from XrmToolBox.

Once that is successfully connected, you will be asked to give a name to identify the connection, and then you will see the list of connections available. Select the connection and click OK. This means you are now connected to the Dynamics 365 developer instance. See Figure 3-13.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig13_HTML.jpg
Figure 3-13

Dynamics 365 connections listed in XrmToolBox

Now, let’s install the plugin to configure the autonumbering. As shown in Figure 3-14, click the Tools menu and select Plugin Store. You will see the Auto Number Manager plugin list.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig14_HTML.jpg
Figure 3-14

XrmToolBox: Auto Number Manager

Click the Install button on the toolbar of the plugin window, and the plugin will be installed to your local plugin list. As shown in Figure 3-15, select the plugin, and you will be directed to the configuration page. On this configuration form, you must enter the following information:
  • Solution: When you are successfully connected to the Dynamics 365 instance, the plugin will list all the solutions in your instance. Select the solution patch you have created to configure the autonumbering.

  • Entity: Select the entity for which you want to configure the autonumbering field.
    • You have two options: either you can create a new autonumber field by clicking the New Field button or you can select an existing field and update it with the autonumber you require, which is what you will be doing here to the Account Number field of the Member entity.

    • Next, define the number format. You can click the snippet, and it will enter the snippet in the field. For this example, enter the prefix SBMA, a sequence number with a length of 6 digits, and a random string.

  • Seed: This is the starting number of the sequence, and you will see the sample number that is generated when the new records are created.

After setting these values, click the Update button, and the settings will be applied to the autonumber field.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig15_HTML.jpg
Figure 3-15

Autonumber configuration window

When updating, you will be warned that autonumbering will make the field read-only across all the forms; click OK. In this example, you are updating an existing field and entering a seed number; it will also warn you about duplicate data. If you have duplicate data, you should create a new field. Since in this example you are using a fresh instance, it is OK.

So, when you create the new record, the account number will be generated as per the configuration. See Figure 3-16.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig16_HTML.jpg
Figure 3-16

New account number generated based on the configuration

Similarly, you can create autonumbering for all the required entities. The Member entity is a system entity, so in the next example, let’s look at setting an autonumber for the event code in the Event entity, which is a custom entity. First, select the entity from the Entity drop-down in the Auto Number Manager and set the configuration as you did in the previous example. See Figure 3-17.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig17_HTML.jpg
Figure 3-17

Setting an event code for the Event entity

It is good to keep the autonumber format unique to each entity, but you should create some standards across the autonumbers that you create. In this example, the last part of the code contains the date and time for the event. As shown in Figure 3-18, the new event record will be created with the event code.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig18_HTML.jpg
Figure 3-18

Event code configured

Likewise, you can select all the relevant entities and add the autonumber as per the end-user requirements. Finally, check in the solution to Azure DevOps and release it to the target environment. In the next section, you will look into some of the basic validation techniques provided by Dynamics 365.

Basic Validations

When entering data, there is always a possibility of entering invalid or incorrect data into the system, which will cause incorrect transactions and outputs. Therefore, whatever system you develop, data validations are a must. In this section, we will be looking at a few of these techniques.

Setting a Field as Required

This is one of the basic forms of validations that will make sure all the relevant information for the record is submitted. For instance, on the event form, Event Code, Name, Event Status, Start Date, and End Date are defined as required fields, meaning that the user must enter data in those fields to describe the event. As shown in Figure 3-19, if you miss a field, the application will notify you.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig19_HTML.jpg
Figure 3-19

Required field validations

Calculated Fields

These types of fields are ideal for performing simple calculations, and they help the user avoid making simple mistakes at the data entry. For instance, in the SBMA application, when a membership is created, it is required that the Membership Renewal Date field should be populated. When you create the field, you have to set the field as a calculated field by setting Field Type to Calculated, as illustrated in Figure 3-20.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig20_HTML.jpg
Figure 3-20

Setting up a Calculated field

Click the Edit button to configure the settings. In this example, you will be using Membership Start Date as the source field to calculate the renewal date. In Figure 3-21, you are validating whether Membership Start Date has a value and then whether it is greater than or equal to the CreatedOn value. If the conditions are true, then set Renewal Date to be 12 months past the Membership Start Date value. Besides AddMonths, there are several other functions available: AddMonths, AddHours, Concact, DiffNDays, DiffNMonths, SubstractDays, SubstractMonths, etc.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig21_HTML.jpg
Figure 3-21

Setting the conditions for the calculated fields

Once saved and published, these settings will be applied to the renewal date field, and the field become read-only. Figure 3-22 illustrates a record created, and the renewal date is set as expected.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig22_HTML.jpg
Figure 3-22

The renewal date is set based on the Membership Start Date field.

Since the execution occurs on the server side, the users will see the changes only after the save event is triggered, which is when the user clicks Save. Also, the calculated fields are read-only and do not consider the end user’s security roles. Note that there are several limitations with calculated fields such as they cannot trigger workflows or plugins on calculated fields, duplicate detection rules are not triggered, etc. You can find out more at https://docs.microsoft.com/en-us/previous-versions/dynamicscrm-2016/administering-dynamics-365/dn832103(v=crm.8)#Considerations .

Rollup Fields

Like calculated fields, rollup fields are an exciting feature introduced recently that have reduced the volume of code required. Rollup fields are accumulated values computed over a set of records in relation to a record such as the total number of registrations for a given event. For example, the event organizers may want to know the number of paid registrations, payment pending registrations, total number of attendance, and cancellations. All these can be considered as event statistics, and recording them with the event provides insight about the event so the planners can make critical decisions. Therefore, calculating these values should be automated and ensure the values are correct. In this example, you will be categorizing these fields into a tab on the form by inserting a tab.

For this example, you will group the Event Statistics fields in a separate section. Remember that when you create these fields, you must set Field Type to Rollup. Once the fields are added to the form, the form will look like something like Figure 3-23, where the fields are grouped into a separate tab.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig23_HTML.jpg
Figure 3-23

Rollup fields on the Event form

To configure the rollup fields, you should click the Edit button next to the Field Type property. As shown in Figure 3-24, you will be setting up the total registration for the given event. The source entity is by default selected, and you can select the related entity. In this example, it is the Event Registrations entity. Next, you can add filters, but for the total count of registrations, this is not required because it is the count of all the registrations. Once you’re done setting this up, save and close the form.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig24_HTML.jpg
Figure 3-24

Setting up rollup fields

As shown in Figure 3-25, you can simply select the required filter to pick up the records and set up the rollup fields with filters.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig25_HTML.jpg
Figure 3-25

Setting up rollup fields with filters

After adding a few registrations, you should open a particular event and hover your mouse over each statistic field. You should be able to see a Refresh button, as shown in Figure 3-26. When you click it, the field will be updated with the values based on the rollup settings. Also, you can navigate to Settings ➤ System Jobs and look for the system job with the name “Calculate rollup fields for the <Entity Name> entity.” Open the job, and in the Actions menu, select Modify Recurrences. In the pop-up window, you can change the frequency of the field refresh to make sure the end users will see the latest values.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig26_HTML.jpg
Figure 3-26

Rollup field updated

Similar to calculated fields, the rollup fields are read-only, and they will not take the user’s security settings. You can define only 100 rollup fields per organization and only 10 per entity. You can find out more about rollup fields at https://technet.microsoft.com/en-us/library/dn832162.aspx .

Business Rules

When business rules were first introduced, users, especially power users, greeted them with great pleasure because they reduce the amount of JavaScript and plugin code required. They are effective in setting up fast-changing business rules while avoiding the trouble of writing complex code snippets. This is useful in scenarios where a rule is scoped at the entity level. Business rules are capable of showing or hiding fields, enabling/disabling fields, validating data and showing error messages, setting field values, etc.

To set up the business rules, open the solution patch, and select the entity where you want to apply the rule. Next, click Business Rules in the left pane and click the New Business Rules button in the grid, as shown in Figure 3-27.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig27_HTML.jpg
Figure 3-27

Creating a new business rule

When click the New Business Rule button, the business rules designer window will be displayed. The design window is used to define the rule as a graphical workflow. In the left corner of the design area, there is a mini-map that enables you to quickly navigate to components in the workflow. You can drag and drop components from the Components tab on the right. The Properties tab next to the Components tab allows you to set the conditions and the properties of each component. For instance, for a condition component, you will have to define the condition on the Properties tab.

One thing to keep in mind is that a business rule always starts with a condition. When you click the component, you can see the properties. For instance, as shown in Figure 3-28, you can check whether the start date is greater than the end date. If it is, then the message will be displayed next to the field.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig28_HTML.jpg
Figure 3-28

Designing the business rule

After defining, you have to save and then click the Activate button in the toolbar of the business rules grid, as shown in Figure 3-29. The business rule will not take effect until you do so. Finally, as always, publish the customizations.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig29_HTML.jpg
Figure 3-29

Activating a business rule

When the user enters a start date greater than the end date, then as per the business rule, it will display the error message next to the field. See Figure 3-30.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig30_HTML.jpg
Figure 3-30

Display error message

In the next example, you will see how to lock and unlock fields based on a state. The scenario is that when Event Registration Status is set to Paid only, the Attendance Status field will be enabled. This is to ensure only the paid registrations will be able to attend a given event. As explained previously, open the business rules designer and create the rule, as shown in Figure 3-31.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig31_HTML.jpg
Figure 3-31

Business rules designer: enabling/disabling fields

In this design, we have used two condition components. The topmost one will check whether the registration status is Paid and, if so, unlock the field. For the second condition, which is the “else-if” part of the flow, it will check whether the registration status is Pending Payment or Cancelled and lock the field if either is true. Once the rule is configured, you have to save it, activate it, and publish all the customizations. On the designer screen, you can see that when the status is Pending/Cancelled, a lock icon appears next to the Attendance Status field, as shown in Figure 3-32.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig32_HTML.jpg
Figure 3-32

Field locked

When the registration status is set to Paid, then the field will be enabled/unlocked, as shown in Figure 3-33.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig33_HTML.jpg
Figure 3-33

Field unlocked

You should know a few additional things about business rules. In the top-right corner of the business rules designer, there is an option to select the scope of the business rule, which was set to All Forms in the previous examples. This means that if there is more than one form, then all the forms will adhere to the business rules defined, and the rules will apply to the client side only. But if you want the rule to be available on the server side, when operating data outside of the form such as in grids, the Web API, the SDK, and bulk data imports, then you will have to set the scope to Entity. In addition to these nice features, there are few limitations.

First, there is a limit of 10 “if-else” conditions per business rule, and the rules cannot be applied to tabs or sections. The rules will be executed only with on-change and on-load events and will not fire with on-save events unless the scope is set as Entity. Finally, conditions cannot contain a mixture of AND and OR; they must be either one or the other. For additional information about business rules, please visit https://docs.microsoft.com/en-us/dynamics365/customer-engagement/customize/create-business-rules-recommendations-apply-logic-form .

JavaScript and TypeScript

When it comes to Dynamics 365 customizations, JavaScript is an essential component that is capable of providing that extra layer of customization to the client side. Being a client-side programming language, JavaScript enables you to do complex validations, record manipulation, and validation on the client side. But the catch is that when you continue to write JavaScript library after library, it becomes more and more complex and can easily end up as spaghetti code in no time. To avoid this, you must have a great deal of programming skills. Even though there are other techniques such as business rules, calculated fields, rollup fields, etc., to limit the client-side code, there are situations where you must write JavaScript to meet specific requirements.

With the Dynamics 365 v9.x release, Microsoft has made some changes to the client API object model and deprecated some of the existing client APIs. Compared to the changes introduced in CRM 2011, these are not significant changes. Everything that was used before is still there, but things have been moved around to add more consistency. You can find more about these changes at https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/clientapi/understand-clientapi-object-model .

Let’s jump into an example. This book will present two versions of this example: what it is used to be and how it is now. First, let’s look at the scenario. There is a requirement to set the membership start date to today’s date. The objective is to ensure that the date is always today or in the future and to eliminate past dates being entered. To begin with, create a new solution to hold the JavaScript code and other web resources. See Figure 3-34.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig34_HTML.jpg
Figure 3-34

Creating a separate solution to hold the JavaScript and other web resources

JavaScript Example

You will be writing the JavaScript code in Visual Studio in this example, so let’s open the solution. Figure 3-35 illustrates the JavaScript that is in the SBMA.Common namespace. As shown in the following code, writing JavaScript in this way is essential because as a best practice, the code needs a good structure, which avoids collisions with other code:
SBMA.Common.setCurrentDate = function () {
   //Get the current date
   //set membership start date for today
   var renewalDate = Date.now();
   Xrm.Page.getAttribute('sbma_membershipstartdate').setValue(renewalDate);
}
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig35_HTML.jpg
Figure 3-35

Wiring JavaScript to the form

Now let’s see how this can be converted to the new object model. This is a working example, but this book is focused on the new JavaScript object model, and all JavaScript examples are written in the new way.
var SBMA = SBMA || {}
SBMA.Common = SBMA.Common || {};
/**
 * This method populates membership renewal date in 1 year from the created date.
 * Executes at page load event.
 * @returns {Void}
 */
SBMA.Common.setCurrentDate = function (executionContext) {
    var formContext = executionContext.getFormContext();
    //set membership start date for today
    var membeshipStartDate = new Date();
    formContext.getAttribute('sbma_membershipstartdate').setValue(membeshipStartDate);
}

The client-side code is triggered with events, which means you should connect the JavaScript code/function to a specific event such as OnSave, OnLoad, etc. Generally, you can use a JavaScript function, which is also known as an event handler, and each handler may or may not have parameters. These event handlers can be associated with the events using the GUI, but for those that are not available via the GUI, you should use the client API methods, which provide the mechanisms to call the event handlers. These methods can be used to collaborate with business process flow control, manage form navigation, get/set attribute values, communicate with multiple forms per entity, etc.

As you can see from the previous code snippet, nothing has significantly changed. But when you wire up the JavaScript after deployment, you will have to select the checkbox “Pass execution context as first parameter.” Then follow these steps:
  1. 1.

    Upload your JavaScript as a web resource to Dynamics 365 for Customer Engagement. In your new solution, select the web resources in the left pane and click New on the grid toolbar.

     
  2. 2.

    Provide the name and display name, set Type as Script (Jscript), set Language to English, and browse your code library. Click Save.

     
  3. 3.

    Close the web resources window, and in the Solution window, click Publish All Customizations.

     
  4. 4.

    Now, let’s wire up the script to the OnLoad event of the form. Open the form via the form editor window. In the ribbon, click the Form Properties button, and in the window that pops up, add your library on the Form Libraries tab.

     
  5. 5.

    On the Event Handlers tab, select FormLoad as the event and add your function.

     
  6. 6.

    When adding the function, you must make sure you are passing executionContext as the first parameter. To do this, select the “Pass execution context as first parameter” checkbox.

     
After setting up these customizations, save and publish them. When you load the Membership form, you can see the Membership Start Date field is set to the current date. See Figure 3-36.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig36_HTML.jpg
Figure 3-36

Membership Start Date is set to the current date

Now, if you look at the function that you wrote, you can use it only with the Membership Start Date field of the Membership form because within the function, you are hard-coding the field name. But there are so many other start date fields where you can use the same logic. To make the function reusable, pass the field name as a parameter to the function, as shown here:
 var SBMA = SBMA || {}
SBMA.Common = SBMA.Common || {};
/**
 * This method populates membership start date for today.
 * Executes at page load event.
 * @returns {Void}
 */
SBMA.Common.setCurrentDate = function (executionContext, fieldName) {
    var formContext = executionContext.getFormContext();
    //set membership start date for today
    var membeshipStartDate = new Date();
    formContext.getAttribute(fieldName).setValue(membeshipStartDate);
}
In this approach, when you wire the function to the event, you must pass the field name as the parameter, as shown in Figure 3-37.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig37_HTML.jpg
Figure 3-37

Passing the field name as a parameter

TypeScript Example

When you have to write more complex JavaScript, the code will become more complex and will be difficult to maintain. The readability of your code will also degrade. In such scenarios, TypeScript is an ideal choice. It is not a new language, but it is the next generation of writing JavaScript code. The coolest thing about TypeScript is that you will be writing ES9 features that will be transpiled to ES6. You can learn more about TypeScript at https://www.typescriptlang.org/docs/home.html . Explaining TypeScript in detail is beyond the scope of this book, but you will learn how to write a simple TypeScript and transform it via the Transpiler into JavaScript that can be used with Dynamics 365.

To begin with, you must install NodeJS. You can download NodeJS at https://nodejs.org/en/ . You also need to install the Open Command Line extension to Visual Studio. You can do this through the NuGet package manager. Next, you can add the TypeScript compiler to the Web Resources project of your solution. See Figure 3-38.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig38_HTML.jpg
Figure 3-38

TypeScript compiler

Now, right-click the Webresources solution, and select Add ➤ Add New Item. From the list of file types, select TypeScript Json Configuration File. Add the CompileOnSave option and set it is true, as shown here:
{
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5"
  },
  "compileOnSave": true
  "exclude": [
    "node_modules",
    "wwwroot"
  ]
}
Now, select the Webresources project and press Alt+spacebar to open the command line. This will open the command prompt to your web resources project. Type in the npm init command to generate the package.json file. Accept all the defaults, and the JSON file will be generated.
{
  "name": "sbma.webresources",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "npm": "^6.4.1"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

The next step is to install the TypeScript definitions for the Dynamics 365 client-side SDK. In the same console window, enter the following command: npm install - -save @types/xrm.

This command will install the node_modules folder in your Webresources project, as shown in Figure 3-39.
../images/471991_1_En_3_Chapter/471991_1_En_3_Fig39_HTML.jpg
Figure 3-39

Node modules for XRM installed to the project

Now, your project is ready, and you can start writing TypeScript. In the src folder, add a new item of type TypeScript. You will write the same JavaScript as the previous example to demonstrate how it works.
namespace SBMA
{
  export class CommonJs
  {
   public setCurrentDate(executionContext: Xrm.Page.EventContext, fieldName: string)
    {
      var formContext = executionContext.getFormContext();
      //Get Current Date
      var currentDate = new Date();
      //Set the current date to the field
      formContext.getAttribute(fieldName).setValue(currentDate);
    }
  }
}
When you save the work, the JavaScript file will be generated, which can be deployed to Dynamics 365.
var SBMA;
(function (SBMA) {
  var CommonJs = /** @class */ (function () {
    function CommonJs() {
    }
    CommonJs.prototype.setCurrentDate = function (executionContext, fieldName) {
    var formContext = executionContext.getFormContext();
    //Get Current Date
    var currentDate = new Date();
    //Set the current date to the field
    formContext.getAttribute(fieldName).setValue(currentDate);
   };
   return CommonJs;
 }());
SBMA.CommonJs = CommonJs;
})(SBMA || (SBMA = {}));
//# sourceMappingURL=SBMACommon.js.map

In the upcoming chapter, the book will use TypeScript instead of JavaScript in the examples.

Summary

In this chapter, you looked at form customizations, autonumbering, calculated fields, rollup fields, business rules, and JavaScript to ensure the validity of data entry. The chapter also discussed the new changes introduced to the JavaScript object model. Finally, the chapter looked at how to use TypeScript to make the client-side scripting more exciting. In the next chapter, you will be looking at automating the business processes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset