Showing posts with label Webresource. Show all posts
Showing posts with label Webresource. Show all posts

Switch Form Type Conditionally Using JavaScript(JS) in Dynamics 365

 In Dynamics 365, sometimes it could be a little overwhelming for some users to switch to the correct form when there are many types of forms for a specific entity(table).

For example, if the form type could be switched automatically when CUSTOMER filed value is changed, below JS could be your reference.

Applied Version:

  • Microsoft Dynamics 365 (on-premises) v9.0 or later
  • Microsoft Dynamics 365 Online

Trigger scenerio:

1. Form - Load

2. Filed: CUSTOMER - Changed

Sample Code:

function SwitchFormByCustomerLevel(executionContext)
{
    var form = executionContext.getFormContext();
    var formOpType = form.ui.getFormType();
   
    // variable to store the name of the form
    var FormShowType;

    debugger;
   
    // get the customer level picklist field
    var customerLevel = form.getAttribute("field_Customer_Level").getText();
    if(customerLevel == null )
    {
            return;
    }


    // switch statement to assign the form to the picklist value
    //change the switch statement based on the customer level picklist values
    switch (customerLevel)
    {        
        case "Gold":
            FormShowType = "Form - Gold";
            break;

        case "Silver":
            FormShowType = "Form - Silver";
            break;
           
        case "VIP":
            FormShowType = "Form - VIP";
            break;
                   
        default:
            //Assume Form Name is same with Product Type Name
            FormShowType = customerLevel;
    }

    // Current form's label
    var CurrentFormLabel = form.ui.formSelector.getCurrentItem().getLabel();

    //check if the current form is the form supposed to be displayed
    if (CurrentFormLabel != FormShowType)
    {
        var items = form.ui.formSelector.items.get();

        if (items == null)
        {
            console.log("Could Not Find Form List");
            return;
        }

        for (var i in items)
        {
            var item = items[i];
            var itemId = item.getId();
            var itemLabel = item.getLabel()

            if (itemLabel == FormShowType)
            {                    
                //navigate to the form
                item.navigate();
                break;
            } //endif
        } //end for    
    } //endif      
} //end function