Category Archives: Power Platform & Dynamics 365 – Client Side Code

Microsoft Dynamics 365: Counting Sub-grid Records and Enabling Users to Hide Empty Sub-grids

In Microsoft Dynamics 365, we can use sub-grids to present data to users in a tabular format. This is a nice and compact way of displaying data. However, sometimes there is no data in those sub-grids to display and the end users might prefer to get back that space and optimize the space on the form. In this blog post, we cover how we can dynamically obtain the number of records in a sub-grid using JavaScipt and use that information to give end users the flexibility to optimize the space on forms by hiding empty sub-grids.

There are two types of sub-grids on Dynamics 365 forms:

  • Read-only sub-grids: Show data in a tabular format but do not allow users to edit data directly on the sub-grid. To edit the data, users have to double click on the record in the grid to open the form, edit the data, and then save it.
  • Editable sub-grids: Apart from showing data in a tabular format, editable sub-grids offer rich inline editing capabilities on web and mobile clients including the ability to group, sort, and filter data within the same sub-grid so that you do not have to switch records or views. In addition to providing all these extensive editing capabilities, editable sub-grids still honor the read-only sub-grid metadata and field-level security settings as well as the general Microsoft Dynamics 365 security model.

Summary of the key syntax

Here is a high-level summary of the main Microsoft Dynamics 365 JavaScript syntax covered in this blog post.

  • Count the number of records in sub-grid, where <subgridName> is the logical name of the sub-grid :
    formContext.getControl("<subgridName>").getGrid().getTotalRecordCount();
  • Remove the blank option in an option set, where <optionsetName> is the logical name of the option set:
    formContext.getControl("<optionsetName>").removeOption("");
  • Get the option set’s selected value , where <optionsetName> is the logical name of the option set:
    formContext.getAttribute("<optionsetName>").getValue();
  • Set the selected value of an option set, where <optionsetName> is the logical name of the option set and <value> is the value the option set will be set to:
    formContext.getAttribute("<optionsetName>").setValue("<value>");
  • Enable/Disable a field, where <fieldName> is the logical name of the field and <Boolean> can be true or false (i.e. true disables field and false enables it):
    formContext.getControl("<fieldName>").setDisabled(<Boolean>);
  • Hide/Unhide section, where <nameOfTab> is the name of the tab containing the section, <nameOfSection> is the name of the section and <Boolean> can be true or false (i.e. true makes the section visible and false hides the section):
    formContext.ui.tabs.get("<nameOfTab>").sections.get("<nameOfSection>").setVisible( <Boolean>);

Application Example: Enabling Users to Hide Empty Sub-grids

Using the code below, we can give end users the flexibility to optimize the space on forms by hiding empty sub-grids. In the code below, the hideEmptyOfficesSubgrid function is the entry point and is called when saving the form and loading the form.

function hideEmptyOfficesSubgrid(executionContext) {  
    var formContext = executionContext.getFormContext();
    var operationsTabName = "tab_operations";
    var officeGridSectionName = "office_grid_section";
    var officeGridName = "office_subgrid";
    var enableOfficeGridName = "hos_enableofficesgrid";
    var no = 183840000;
    var yes = 183840001;
    formContext.getControl(enableOfficeGridName).removeOption(""); 

    setTimeout(function () {
        if (formContext.getControl(officeGridName) != null && formContext.getControl(officeGridName) != undefined) {
            var count = formContext.getControl(officeGridName).getGrid().getTotalRecordCount();
            var enableOfficeGrid = formContext.getAttribute(enableOfficeGridName);
            var enableOfficeGridCtrl = formContext.getControl(enableOfficeGridName);
            var officeGridSection = formContext.ui.tabs.get(operationsTabName).sections.get(officeGridSectionName);
            disableSubgridControlField(count, enableOfficeGridCtrl);
            hideEmptySubgrid(count, enableOfficeGrid, officeGridSection, no, yes);
        }
    }, 5000);      
}

function disableSubgridControlField(count, subgridCtrlField) {  
    if (count <= 0) 
        subgridCtrlField.setDisabled(false);       
    else if (count > 0) 
        subgridCtrlField.setDisabled(true);
}

function hideEmptySubgrid(count, subgridCtrlField, subgridSection, no, yes) {  
    if (areTheseTwoInputsIdentical(subgridCtrlField.getValue(), yes)) 
        subgridSection.setVisible(true);       
    else if (count <= 0 && (areTheseTwoInputsIdentical(subgridCtrlField.getValue(), no) || subgridCtrlField.getValue() == null)) 
        subgridSection.setVisible(false);
    else if (count > 0 && areTheseTwoInputsIdentical(subgridCtrlField.getValue(), no)) {
        subgridCtrlField.setValue(yes);
        subgridSection.setVisible(true);
    }
}

function areTheseTwoInputsIdentical(input1, input2) {
    if (input1 == input2) 
        return true;
    else 
        return false;
}

How the code works

In the first image below, the account record is not enabled for Offices (i.e. the value of Enable Office Grid option set is No). Therefore, Offices grid is empty and hidden.
Account record not enabled for Offices sub-grid

After enabling the account record for Offices by changing the value of the option set field, “Enable Offices Grid” to Yes, the Offices sub-grid shows up and we can add offices to the sub-grid as shown below. The “Enable Offices Grid” field controls the appearance and disappearance of the Offices sub-grid.
Account record enabled for Offices sub-grid

As shown in the image above, the Enabled Office Grid option set is locked as soon as we add and save records to the Offices sub-grid. This prevents a scenario of logic inconsistency where an account record has offices in it’s sub-grid and the user proceeds to change the value of the Enable Offices Grid field to No. Therefore, the Enable Office Grid field value can only be changed back to No and hide the Offices grid after the sub-grid emptied up and there are no more records in it. Therefore, using the solution above, end users can be empowered with the option of hiding empty sub-grids and optimize the space on the form.

Microsoft Dynamics 365: Varying Form Behavior On Form-type and Save-mode

Microsoft Dynamics 365 offers the ability to vary the behavior of forms based on the form type and how the form is saved, using JavaScript. In this blog post, we cover how we can make use of this flexibility offered by the platform to deliver unique solutions for end users.

Summary of the key syntax

Here is a high-level summary of the main Microsoft Dynamics 365 JavaScript syntax covered in this blog post.

  • Getting the type of form:
    formContext.ui.getFormType();
  • Hide a tab on a form (where “TabName” represents the name of the tab you would like to hide):
    formContext.ui.tabs.get("TabName").setVisible(false);
  • Get the object with methods to manage the Save event:
    executionContext.getEventArgs();
  • Get the form Save Mode:
    executionContext.getEventArgs().getSaveMode();
  • Inhibit the default save behavior on a form
    executionContext.getEventArgs().preventDefault();
  • Check if the default save behavior was inhibited
    executionContext.getEventArgs().isDefaultPrevented();
  • Get the form context
    executionContext.getFormContext();

Form Type

To get the Form Type, you use the following JavaScript code:

formContext.ui.getFormType();

Here are the different Dynamics 365 form types and their respective JavaScript return values:

Form type Return Value
Undefined0
Create1
Update2
Read Only3
Disabled4
Bulk Edit6

Application Example: Varying form behavior on Form Type

In this application example, we will hide the Products and Services tab on the Create type form (with JavaScript Return Value = 1). However, it will be still be visible on all other applicable form types. This prevents users from adding information to the Products and Services tab before a Contact record has been created and saved. Therefore, the user must first create the Contact record (using the Create form type) and after the record has been created, the users will be presented with the Update form type (with JavaScript Return Value = 2) and will be able to access the Products and Services tab as well as its contents.

The Contact entity’s create form type will look similar to this (i.e. the Products and Services tab is hidden):
Contact - Create form type

In contrast, the Update form type still shows the Products and Services tab.
Contact - Update form type

Here is the code to executes the requirement above.

//Hide Products and Services tab on Create form 
function HideProductsServicesTab(executionContext) {   
  //Get form context   
  var formContext = executionContext.getFormContext();   
  //Get form type   
  var formType = formContext.ui.getFormType();   
  //If formtype is Create, hide Products and Services tab on form     
  if (formType == 1) {
    formContext.ui.tabs.get("productsandservices").setVisible(false);   
  }   
  //To see the form type return value in your browser console
  console.log("Form type = " + formType); 
}

Save Mode

To get the form’s Save Mode, you use the following JavaScript code:

executionContext.getEventArgs().getSaveMode();

Here are Dynamics 365’s different Save Modes and their respective JavaScript return values as well as the applicable entities.

Entity Save Mode Return Value
AllSave1
AllSave and Close2
AllDeactivate5
AllReactivate6
EmailSend7
LeadDisqualify15
LeadQualify16
User or Team owned entitiesAssign47
ActivitiesSave as Completed58
AllSave and New59
AllAuto Save70

Application Example: Varying form behavior on Save Mode

Here is an example of how you can vary the form’s behavior on the Save Mode.

//Inhibit auto save functionality on a form
function InhibitAutoSave(executionContext) {
  var eventArgs = executionContext.getEventArgs();
  //To see the Save Mode return value in your browser console
  console.log("Save Mode = " + eventArgs.getSaveMode());
  //If save mode is 'Save and Close' or 'Auto Save', inhibit default behavior i.e. save 
  if (eventArgs.getSaveMode() == 2 || eventArgs.getSaveMode() == 70) {
    eventArgs.preventDefault(); 
  } 
  //To see if the auto save behavior was prevented in your browser console
  console.log("Default behaviour prevented: " + eventArgs.isDefaultPrevented());
 }

If you have some unsaved changes on a form, the code above inhibits the regular form auto save behavior as well as inhibits the regular Save and Close auto save behavior, that you ordinarily get when you navigate away from from a form with unsaved changes. Instead of auto-saving (i.e. the default behavior), if you try to navigate away from a form with an unsaved changes, the JavaScript code above will block the auto save behavior and offer you the pop up notification below. If you choose “OK”, you will loose all your unsaved changes, and if you choose “Cancel”, you will remain the same form. With the default auto save behavior inhibited, users have to manually save the form, by clicking on the Save button or using the keyboard shortcut: “Control + S”.
Auto Save Inhibited: Do you want to loose your changes?

What if you want to inhibit the auto-save behavior throughout your Dynamics 365 organization (i.e. disable auto-save on all forms), instead of a specific form? It would be inefficient to implement the JavaScript code above on all forms across all your Dynamics 365 organization entities. An efficient way execute such a requirement (i.e. on all forms) is to:

  1. Go to Settings > Administration.
  2. Click on System Settings.
  3. Click on the General tab
  4. Set the Enable auto save on all forms option, to No.
  5. Click OK, in the footer of the window.

Disabling Auto Save in a Dynamics 365 Organization

Microsoft Dynamics 365: Notifications Using JavaScript

In Microsoft Dynamics 365, sometimes we need to send automated notifications to end users. These notifications can come from the server (i.e. back-end automation using workflows, plugins, etc) or from the code loaded in the user’s web browser (i.e. front-end or client side automation using JavaScript). The latter notifications will make up the scope of this blog post. We will cover form level notifications (with and without persistence), field level notifications and popup boxes notifications using JavaScript.

Summary of the key syntax

Here is a high-level summary of the main Microsoft Dynamics 365 JavaScript notifications demonstrated in this blog post.

  • Form Level Notifications – Set Notification
    formContext.ui.setFormNotification(message, messageType, uniqueId);
  • Form Level Notifications – Clear Notification
    formContext.ui.clearFormNotification(uniqueId);
  • Field Specific Notifications – Set Notification
    formContext.getControl(fieldLogicalName).setNotification(message, uniqueId);
  • Field Specific Notifications – Clear Notification
    formContext.getControl(fieldLogicalName).clearNotification(uniqueId);
  • Alert Box
    alert(message);
  • Confirmation Box
    confirm(message);
  • Prompt Box
    prompt(message, sampleText);

Form Level Notifications

Here is an example of form level notifications applied to the Contact entity’s form. The notification options available at form-level are: Error, Warning and Information. These notification options have different icons as shown in the image below.
Page Level Notification

Below is the JavaScript code that was used to generate the notifications shown in the image above. Therefore, every time a user opens up a contact form, these notifications will always appear at the top of the form.

function FormLevelNotification(executionContext) {
    var formContext = executionContext.getFormContext();    
    formContext.ui.setFormNotification("Example of an ERROR notification. ", "ERROR");
    formContext.ui.setFormNotification("Example of a WARNING notification. ", "WARNING");
    formContext.ui.setFormNotification("Example of an INFORMATION notification.", "INFO");    
}

Instead of having persistent notifications (ever present whenever a user opens the contact form), it is commons for organizations to implement a modified version of these notifications i.e. where the notifications above expire after a specifies amount of time. Therefore, every time a user opens a contact form (or any other form where this functionality is implemented), they get notifications similar to image above, but after a specified amount of time, the notifications disappear and user end up with form like the one below.
Page Level Notification Expired

This modified option where the form level notifications disappear after a specified amount of time can be accomplished using the code below. In code below, I have chosen an expiration time of 30 seconds. Therefore, the form level notifications would only persist for the first 30 seconds after a user opens up a contact form.

function FormLevelNotificationWithExpiration(executionContext) {
    var formContext = executionContext.getFormContext();
    var notificationTime = 30000; // 30 seconds in milliseconds 
    var errorId = "error";
    var warningId = "warning";
    var infoId = "info";
    //Set notifications
    formContext.ui.setFormNotification("Example of an ERROR notification. ", "ERROR", errorId);
    formContext.ui.setFormNotification("Example of a WARNING notification. ", "WARNING", warningId);
    formContext.ui.setFormNotification("Example of an INFORMATION notification.", "INFO", infoId);

    //Clear the notifications after the specified amount of time time e.g. 5 seconds
    setTimeout(
        function () {      
            formContext.ui.clearFormNotification(errorId);
            formContext.ui.clearFormNotification(warningId);           
            formContext.ui.clearFormNotification(infoId);
        },
        notificationTime
    );
}

Field Specific Notifications

To guide users in completing a form correctly, you can provide field specific notification like the ones below. The example below shows the subscription section on the Contact entity’s form. Logically, the Subscription Start Date must precede the Subscription End Date. Whenever a users enters a Subscription End Date that precedes the Subscription Start Date, the field level notifications appear advising the user that “The Subscription End Date cannot be before Subscription Start Date” as show below.
Field Level Notifications

The functionality shown in the image above was accomplished using the following JavaScript functions.

//Validation of the TV Subscription Dates
function TvSuscriptionDateValidation(executionContext) {
    var formContext = executionContext.getFormContext();
    var tvSubStartDateLogicalName = "hos_tvsubstartdate";
    var tvSubEndDateLogicalName = "hos_tvsubenddate";
    var startDateField = formContext.getAttribute(tvSubStartDateLogicalName);
    var endDateField = formContext.getAttribute(tvSubEndDateLogicalName);
    var endDateFieldControl = formContext.getControl(tvSubEndDateLogicalName);
    var startDate, endDate;

    if (startDateField != null && endDateField != null) {
        startDate = startDateField.getValue();
        endDate = endDateField.getValue();
        if (IsDate(startDate) && IsDate(endDate) && startDate > endDate ) {
            //Display an error message if the dates entered are logically invalid.
            endDateFieldControl.setNotification("The Subscription End Date cannot be before Subscritpion Start Date.", "tvEndDate");
            endDateField.setValue(null);
        }
        else {
            endDateFieldControl.clearNotification("tvEndDate");            
        }
    }
}

//Verify that the field contains date instead of a null value
function IsDate (input) {
    if (Object.prototype.toString.call(input) === "[object Date]") {
        return true;
    }   
    return false;
}

Popup Notifications

Sometimes you really to get the user’s attention, that is, prevent them from interacting with the form until they have acknowledged your message. To accomplish that endeavor using JavaScript, you can use the popup boxes. There are 3 types of popup boxes (i.e. alert box, confirmation box and prompt box). In this section, we will show what these popup look like in Dynamics 365 and provide an example of how to implement them.

Alert Box

Here is an example of an Alert Box in Dynamics 365. The user can acknowledge the message by pressing OK and proceed interact with the form.
Alert Box

The functionality shown in the image above was accomplished using the following JavaScript function.

function AlertBox() {
    alert("This is an example of a JavScript Alert window ");

    //Alternatively way of writing an Alert Box with the Window prefix:    
    //window.alert("This is an example of a JavScript Alert window ");
}

Confirmation Box

Here is an example of an Confirmation Box in Dynamics 365. The user is given two options. Depending on the user’s choice, you can proceed to add more logic. In this example, we use an alert box to notify user of the choice that was selected.
Confirmation Box

The functionality shown in the image above was accomplished using the following JavaScript function.

function ConfirmBox() {    
    var confirmationText;
    if (confirm("Would you like to proceed?")) {
        confirmationText = "You pressed OK!";
    } else {
        confirmationText = "You pressed Cancel!";
    }
    //Using the alert notification to show the option selected
    alert(confirmationText);

    //Alternatively way of writing an Confirm Box with the Window prefix:    
    //window.confirm("Press a button: 'OK' or 'Cancel'");
}

Prompt Box

Here is an example of an Prompt Box in Dynamics 365. The user is given a text box where they can enter an answer as well as two options (i.e. OK and Cancel). Depending on the user’s responses, you can proceed to add more logic. In this example, we use an alert box to notify user of the text that was entered, if they click on OK.
Prompt Box

The functionality shown in the image above was accomplished using the following JavaScript function.

function PromptBox() {
    var userText = prompt("Please enter your name below", "This is sample text ");
    //Using the alert notification to show the text entered in the prompt box
    alert("You said your name is: \n" + userText);   

    //Alternatively way of writing an Prompt Box with the Window prefix:
    //window.prompt("Please enter some text below", "This is sample text ");
}

Best Practices and Recommendations

For demonstration purposes in this blog post, I included the notification messages in the code. However, for easier maintenance and to give more flexibility to the end users, who may not be Dynamics 365 software developers, it is recommended to put the notification messages in the Dynamics 365 Configuration Data and then create JavaScript helper function(s) that retrieve the data at runtime using a key. Using this approach, end users with the appropriate security roles can update the JavaScript notification messages anytime without calling upon the services of a Dynamics 365 software developer with JavaScript experience.

Dynamics 365: How To Get and Set Fields on Forms Using JavaScript

In this post, we will cover how to get and set values for fields on Microsoft Dynamics 365/CRM forms. Dynamics 365 has the following types of fields (or datatypes): Single Line of Text, Option Set, MultiSelect Option Set, Two Options, Image, Whole Number, Floating Point Number, Floating Point Number, Decimal Number, Currency, Multiple Lines of Text, Date and Time, Lookup and Customer.

At the time of writing, there are two ways of accessing fields on Dynamics 365 forms i.e. using the formContext JavaScript API and Xrm.Page JavaScript API. However, Microsoft has the following JavaScript API recommendations:

  • Before Dynamics 365/CRM version 9.0, use the Xrm.Page API:
    Xrm.Page.getAttribute(fieldName);
  • Version 9.0 of Dynamics 365/CRM and after, use the formContext API:
    executionContext.getFormContext().getAttribute(fieldName);

With the release of version 9.0 of Dynamics CRM/365, Microsoft announced that it would deprecate the Xrm.Page JavaScript API. For details on how you can transition from the Xrm.Page API to the formContext API, see my earlier post: Quick Guide: Transitioning away from Microsoft Dynamics 365 Xrm.Page JavaScript API. From Xrm.Page to formContext, how you get and set values has not fundamentally changed. However, how you access fields and other form properties has changed.

Single Line of Text

Here is an example of a Single Line of Text field on a Dynamics 365 form:
Single Line of Text field

Here is the JavaScript for getting and setting the value of a Single Line of Text field (Display Name: “Account Number” | Database Name: “accountnumber”):

//Get and Set a Single Line of Text field value
function SingleLineOfTextFieldValue(executionContext) {
    //Get the context of the form
    var formContext = executionContext.getFormContext();
    //The logical name of the field of interest
    var accountNumberFieldLogicalName = "accountnumber";
    //Access the field on the form
    var accountNumberField = formContext.getAttribute(accountNumberFieldLogicalName);
    //Declare the other variables as needed
    var accountNumberFieldValue;

    //Check that field exist on the form before you try to Get/Set its value
    if (accountNumberField != null) {
        // Get the value of the field
        accountNumberFieldValue = accountNumberField.getValue();

        // Set the value of the field
        accountNumberField.setValue("BYA-2019-AIR-0099");
    }
}

Multiple Lines of Text

Here is an example of a Multiple Lines of Text field on a Dynamics 365 form:
Multiple Lines of Text field

Here is the JavaScript for getting and setting the value of a Multiple Lines of Text field (Display Name: “Description” | Database Name: “description”):

//Get and Set Multiple Lines of Text field value
function MultipleLineOfTextFieldValue(executionContext) {
    debugger;
    //Get the context of the form
    var formContext = executionContext.getFormContext();
    //The logical name of the field of interest
    var descriptionFieldLogicalName = "description";
    // Access the description field on the form
    var descriptionField = formContext.getAttribute(descriptionFieldLogicalName);
    //Declare the other variables as needed
    var descriptionFieldValue;
    var exampleText = "\
            To be, or not to be, that is the question:\
            Whether 'tis nobler in the mind to suffer\
            The slings and arrows of outrageous fortune,\
            Or to take Arms against a Sea of troubles,\
            And by opposing end them: to die, to sleep;\
            No more; and by a sleep, to say we end \
            The heart - ache, and the thousand natural shocks \
            That Flesh is heir to ? 'Tis a consummation \
            Devoutly to be wished.To die, to sleep, \
            perchance to Dream; aye, there's the rub, \
            For in that sleep of death, what dreams may come, \
            When we have shuffled off this mortal coil,\
            Must give us pause. "  ;

    //Check that field exist on the form before you try to Get/Set its value
    if (descriptionField != null) {
        // Get the value of the description field
        descriptionFieldValue = descriptionField.getValue();

        // Set the value of the description field
        descriptionField.setValue(exampleText);
    }
}

Whole Number

Here is an example of a Whole Number field on a Dynamics 365 form:
Whole Number Field

Here is the JavaScript for getting and setting the value of a Whole Number field (Display Name: “Number of Employees” | Database Name: “numberofemployees”):

//Get and Set a Whole Number field value
function WholeNumberFieldValue(executionContext) {
    //Get the context of the form
    var formContext = executionContext.getFormContext();
    //The logical name of the field of interest
    var numberOfEmployeesFieldLogicalName = "numberofemployees";
    // Access the field on the form
    var numberOfEmployeesField = formContext.getAttribute(numberOfEmployeesFieldLogicalName);
    //Declare the other variables as needed
    var numberOfEmployeesFieldValue;

    //Check that field exist on the form before you try to Get/Set its value
    if (numberOfEmployeesField != null) {
        // Get the value of the field
        numberOfEmployeesFieldValue = numberOfEmployeesField.getValue();

        // Set the value of the field
        numberOfEmployeesField.setValue(20000);
    }
}

Decimal Number

Here is an example of a Decimal Number field on a Dynamics 365 form:
Decimal Number field

Here is the JavaScript for getting and setting the value of a Decimal Number field (Display Name: “Exchange Rate” | Database Name: “exchangerate”):

//Get and Set a Decimal Number field value
function DecimalNumberFieldValue(executionContext) {
    //Get the context of the form
    var formContext = executionContext.getFormContext();
    //The logical name of the field of interest
    var exchangeRateFieldLogicalName = "exchangerate";
    // Access the field on the form
    var exchangeRateField = formContext.getAttribute(exchangeRateFieldLogicalName);
    //Declare the other variables as needed
    var exchangeRateFieldValue;

    //Check that field exist on the form before you try to Get/Set its value
    if (exchangeRateField != null) {
        // Get the value of the field
        exchangeRateFieldValue = exchangeRateField.getValue();

        // Set the value of the field
        exchangeRateField.setValue(1.35551);
    }
}

Floating Point Number

Here are some examples of Floating Number fields on a Dynamics 365 form:
Floating Number field

Here is the JavaScript for getting and setting the value of a Floating Number field (Display Name: “Address 1: Longitude” | Database Name: “address1_longitude”):

//Get and Set a Floating Point Number field value
function FloatingPointNumberFieldValue(executionContext) {
    //Get the context of the form
    var formContext = executionContext.getFormContext();
    //The logical name of the field of interest
    var longitudeFieldLogicalName = "address1_longitude";
    // Access the field on the form
    var longitudeField = formContext.getAttribute(longitudeFieldLogicalName);
    //Declare the other variables as needed
    var longitudeFieldValue;

    //Check that field exist on the form before you try to Get/Set its value
    if (longitudeField != null) {
        // Get the value of the field
        longitudeFieldValue = longitudeField.getValue();

        // Set the value of the field
        longitudeField.setValue(-79.387054);
    }
}

Currency

Here is an example of a Currency field on a Dynamics 365 form:
Currency field

Here is the JavaScript for getting and setting the value of a Currency field (Display Name: “Annual Revenue” | Database Name: “revenue”):

//Get and Set a Currency field value
function CurrencyFieldValue(executionContext) {
    //Get the context of the form
    var formContext = executionContext.getFormContext();
    //The logical name of the field of interest
    var revenueFieldLogicalName = "revenue";
    // Access the field on the form
    var revenueField = formContext.getAttribute(revenueFieldLogicalName);
    //Declare the other variables as needed
    var revenueFieldValue;

    //Check that field exist on the form before you try to Get/Set its value
    if (revenueField != null) {
        // Get the value of the field
        revenueFieldValue = revenueField.getValue();

        // Set the value of the field
        revenueField.setValue(52000000);
    }
}

Two Options

Here are some examples of Two Options fields on a Dynamics 365 form:
Two Options field

Here is the JavaScript for getting and setting the value of a Two Options field (Display Name: “Email” | Database Name: “donotemail”):

//Get and Set a Two Options field value
function TwoOptionsFieldValue(executionContext) {
    //Get the context of the form
    var formContext = executionContext.getFormContext();
    //The logical name of the field of interest
    var dontAllowEmailsFieldLogicalName = "donotemail";
    // Access the field on the form
    var dontAllowEmailsField = formContext.getAttribute(dontAllowEmailsFieldLogicalName);
    //Declare the other variables as needed
    var dontAllowEmailsValue;

    //Check that field exist on the form before you try to Get/Set its value
    if (dontAllowEmailsField != null) {
        // Get the value of the field
        dontAllowEmailsValue = dontAllowEmailsField.getValue();

        // Set the value of the field to TRUE
        //dontAllowEmailsField.setValue(true);

        // Set the value of the field to FALSE
        dontAllowEmailsField.setValue(false);
    }
}

Option Set

Here is an example of an Option Set field on a Dynamics 365 form:
Option Set field

Here is the JavaScript for getting and setting the value of an Option Set field (Display Name: “Contact Method” | Database Name: “preferredcontactmethodcode”):

//Get and Set a Option Set field value
function OptionsetFieldValue(executionContext) {
    //Get the context of the form
    var formContext = executionContext.getFormContext();
    //The logical name of the field of interest
    var contactMethodFieldLogicalName = "preferredcontactmethodcode";
    // Access the field on the form
    var contactMethodField = formContext.getAttribute(contactMethodFieldLogicalName);
    //Declare the other variables as needed
    var contactMethodValue;

    //Check that field exist on the form before you try to Get/Set its value
    if (contactMethodField != null) {
        // Get the value of the field
        contactMethodValue = contactMethodField.getValue();
        
        // Set the value of the field to FALSE
        contactMethodField.setValue(5);   
    }
}

MultiSelect Option Set

Here is an example of a MultiSelect Option Set field on a Dynamics 365 form:
MultiSelect Option Set field

Here is the JavaScript for getting and setting the values of a MultiSelect Option Set field (Display Name: “Geographical Areas of Operation” | Database Name: “hse_geographicalareasofoperation”) :

//Get and Set a MultiSelect Option Set field value
function MultiSelectOptionsetFieldValue(executionContext) {
    //Get the context of the form
    var formContext = executionContext.getFormContext();
    //The logical name of the field of interest
    var locationFieldLogicalName = "hse_geographicalareasofoperation";
    // Access the field on the form
    var locationField = formContext.getAttribute(locationFieldLogicalName);
    //Declare the other variables as needed
    var locationValue;

    //Check that field exist on the form before you try to Get/Set its value
    if (locationField != null) {
        // Get the value of the field
        locationValue = locationField.getValue();

        // Set the value of the field to the desired values
        locationField.setValue([864700000, 864700003, 864700005, 864700007]);
    }
}

Date and Time

Here are some examples of Date and Time fields on a Dynamics 365 form:
Date and Time fields

Here is the JavaScript for getting and setting the value of a Date and Time field (Display Name: “Follow Up Date” | Database Name: “hse_followupdate”):

//Get and Set a Date and Time field value
function DateAndTimeFieldValue(executionContext) { 
    //Get the context of the form
    var formContext = executionContext.getFormContext();
    //The logical name of the field of interest
    var createdOnFieldLogicalName = "createdon";
    var followUpFieldLogicalName = "hse_followupdate";
    // Access the fields on the form
    var createdOnField = formContext.getAttribute(createdOnFieldLogicalName);
    var followUpField = formContext.getAttribute(followUpFieldLogicalName);
    //Declare the other variables as needed
    var createdOnFieldValue;
    var followUpFieldValue = new Date();
    var numberOfDays = 30;
    var daysMillisecondsConverter = 24 * 60 * 60 * 1000;

    //Check that fields exist on the form before you try to Get/Set its values
    if (createdOnField != null && followUpField != null) {
        // Get the value of the field
        createdOnFieldValue = createdOnField.getValue();

        //Before you use the createdOnFieldValue value, verify that it exists
        if (createdOnFieldValue != null) { 
            //Set the follow up date to 30 days after the record was created
            followUpFieldValue.setTime(createdOnFieldValue.getTime() + (numberOfDays * daysMillisecondsConverter));           
            // Set the value of the field
            followUpField.setValue(followUpFieldValue);
        }        
    }
}

Lookup

Here is an example of a Lookup field on a Dynamics 365 form:
Lookup field

Here is the JavaScript for getting and setting the value of a Lookup field (Display Name: “Account Manager” | Database Name: “hse_accountmanager”) :

//Get and Set a Lookup field value
function LookupFieldValue(executionContext) {
    //Get the context of the form
    var formContext = executionContext.getFormContext();
    //The logical name of the field of interest
    var accountmanagerLogicalName = "hse_accountmanager";
    // Access the field on the form
    var accountmanagerField = formContext.getAttribute(accountmanagerLogicalName);
    //Declare the other variables as needed
    var accountmanagerFieldValue;
    var guid;
    var name;
    var entityName;

    //Check that field exist on the form before you try to Get/Set its value
    if (accountmanagerField != null) {
        // Get the value of the field
        accountmanagerFieldValue = accountmanagerField.getValue();
        //Check if the field contains a value
        if (accountmanagerFieldValue != null) {
            //To get the attributes of the field
            guid = accountmanagerFieldValue[0].id.slice(1, -1);
            name = accountmanagerFieldValue[0].name;
            entityName = accountmanagerFieldValue[0].entityType;
        }

        // Set the value of the field
        accountmanagerField.setValue([{
            id: "4BDB64C8-AA81-E911-B80C-00155D380105",
            name: "Joshua Sinkamba",
            entityType: "systemuser"
        }]);

        //Alternative Approach: Set the value of the field
        //var lookupValue = new Array();
        //lookupValue[0] = new Object();
        //lookupValue[0].id = "4BDB64C8-AA81-E911-B80C-00155D380105";
        //lookupValue[0].name = "Joshua Sinkamba";
        //lookupValue[0].entityType = "systemuser";
        //accountmanagerField.setValue(lookupValue);
    }
}

Customer

Here is an example of a Customer field on a Dynamics 365 form:
Customer field

Here is the JavaScript for getting and setting the value of a Customer field (Display Name: “Main Customer” | Database Name: “hse_maincustomer”):

//Get and Set a Customer field value
function CustomerFieldValue(executionContext) {
    //Get the context of the form
    var formContext = executionContext.getFormContext();
    //The logical name of the field of interest
    var mainCustomerLogicalName = "hse_maincustomer";
    // Access the field on the form
    var mainCustomerField = formContext.getAttribute(mainCustomerLogicalName);
    //Declare the other variables as needed
    var mainCustomerFieldValue;
    var guid;
    var name;
    var entityName;

    //Check that field exist on the form before you try to Get/Set its value
    if (mainCustomerField != null) {
        // Get the value of the field
        mainCustomerFieldValue = mainCustomerField.getValue();
        //Check if the field contains a value
        if (mainCustomerFieldValue != null) {
            //To get the attributes of the field
            guid = mainCustomerFieldValue[0].id.slice(1, -1);
            name = mainCustomerFieldValue[0].name;
            entityName = mainCustomerFieldValue[0].entityType;
        }

        // Set the value of the field
        mainCustomerField.setValue([{
            id: "EE047399-CDE0-E911-B817-00155D380105",
            name: "Avanade",
            entityType: "account"
        }]);

        //Alternative Approach: Set the value of the field
        //var customerValue = new Array();
        //customerValue[0] = new Object();
        //customerValue[0].id = "EE047399-CDE0-E911-B817-00155D380105";
        //customerValue[0].name = "Avanade";
        //customerValue[0].entityType = "account";
        //mainCustomerField.setValue(customerValue);
    }
}