How to Create a Clickable Link in Model Driven App Form Notifications

Dynamics CRM Model Driven Apps provide a powerful platform for building custom business applications that work seamlessly with Microsoft Dynamics CRM services. One of the most important features in Dynamics CRM is the ability to show form notifications to users. Form notifications allow you to alert users when a specific event occurs in your form, there are 3 types of form notifications which you can display to end users i.e. Error, Warning and Information.

Often you may want user to perform a follow-up action on the notification like sending a follow-up email or deactivating the record or simply navigating to some external websites.

In this blog we will try to create a form notification on lead record that will be visible when lead is open for more that 10 days with a clickable button to navigate to email create form.

You will need to pass an additional parameter to setFormNotification api as below specification.

Method used in this blog is not documented on official client API documentation and hence considered as unsupported

Syntax

formContext.ui.setFormNotification(message, level, uniqueId, actions);

Parameter

NameTypeRequiredDescription
messageStringYesThe text of the message.
levelStringYesThe level of the message, which defines how the message will be displayed. Specify one of the following values:
ERROR : Notification will use the system error icon.
WARNING : Notification will use the system warning icon.
INFO : Notification will use the system info icon.
uniqueIdStringYesA unique identifier for the message that can be used later with clearFormNotification to remove the notification.
actionsArray of ObjectsNo Object Contains the following values:
Label: (Optional) String. The label for the action in the message.
Handler: (Optional) Function reference. The function to execute when the action label is clicked.

Create a script

function createFormNotificationWithClickeableLink(executionContext) {
  let formContext = executionContext.getFormContext();
  formContext.ui.clearFormNotification("LeadWarning10Days");
  let createdOn = formContext.getAttribute("createdon").getValue();
  let daysOpen = Math.floor((new Date() - createdOn) / 86400000);
  if (daysOpen > 10) {
    formContext.ui.setFormNotification(
      `This lead has been open since last ${daysOpen}, please send a followup email to customer.`,
      "INFO",
      "LeadWarning10Days",
      [
        {
          Label: "Send Followup Email",
          Handler: createEmail,
        },
      ]
    );
  }
}

function createEmail(executionContext) {
  let formContext = executionContext.getFormContext();
  let entityFormOptions = {};
  entityFormOptions["entityName"] = "email";
  let formParameters = {};
  formParameters["subject"] = "Folloup email from form notification";
  formParameters["description"] =
    "Default values for this record were set programmatically.";

  formParameters["regardingobjectid"] =
    formContext.data.entity.getEntityReference().id;
  formParameters["regardingobjectidname"] =
    formContext.data.entity.getEntityReference().name;
  formParameters["regardingobjectidtype"] =
    formContext.data.entity.getEntityReference().entityTame;
  Xrm.Navigation.openForm(entityFormOptions, formParameters);
}

Call the method on load of the form

Notification with Action Button

Apply custom background color to rows on a PowerApps Grid.

Often there are requirements to apply different background colors to rows of a PowerApps grid based on values on other columns. for example, on leads showing qualified leads records with green, disqualified leads with red and open leads with yellow background color respectively.

We can achieve this by following below steps.

Create the script.

Create a new web resource or use an existing one and copy below function.

function addColor(rowData) {
    if (rowData && rowData !== "") {
        let gridRow = JSON.parse(rowData);
        let rowId = gridRow.RowId;
        let rowSelector = parent.document.querySelectorAll(`[row-id="${rowId}"]`)[1];
        if (rowSelector && gridRow.statecode_Value != null) {
            switch (gridRow.statecode_Value) {
//If model driven app has "Try the new look and feel (preview)" turned on then optionset values are returned as string instead of number
                case 0:
                case "0": {
                    //Open
                    rowSelector.style.backgroundColor = "lightgoldenrodyellow";
                    break;
                }
                case 1:
                case "1": {
                    //Qualified
                    rowSelector.style.backgroundColor = "lightgreen";
                    break;
                }
                case 2:
                case "2": {
                    //Disqualified
                    rowSelector.style.backgroundColor = "lightsalmon";
                    break;
                }
            }
        }
    }
}

Bind script function on view column.

Select a column and click “Change Properties.”

Specify web resource and function name.

Launch PCF control through ribbon button

Build PCF control

We will start with building a simple React PCF control that contains a Fluent ui dialog.

Open cmd or visual studio code terminal and execute following command to initialize pcf control.

pac pcf init -ns Test -n SampleModalPCF -t field

Create a new file HellowWorld.tsx with following code to display a Fluent UI Dialog

import * as React from 'react';
import { Dialog, DialogFooter, DialogType } from '@fluentui/react/lib/Dialog';
import { PrimaryButton } from '@fluentui/react/lib/Button';
const SampleControl = () => {
  const [hiddenDialog, SetHiddenDialog] = React.useState(false);
  return (
    <div>
      <Dialog
        hidden={hiddenDialog}
        dialogContentProps={{ title: "Sample Dialog", subText: "", type: DialogType.close }}
        modalProps={{ isBlocking: false }}
        maxWidth="450"
        onDismiss={() => SetHiddenDialog(true)}
      />
    </div>
  )
}
export default SampleControl;

Update index.ts as below, make sure to not destroy the component.

import React = require("react");
import ReactDOM = require("react-dom");
import {IInputs, IOutputs} from "./generated/ManifestTypes";
import SampleControl from "./HelloWorld";
export class SampleModalPCF implements ComponentFramework.StandardControl<IInputs, IOutputs> {
    private container:HTMLElement;
    private context:ComponentFramework.Context<IInputs>
    /**
     * Empty constructor.
     */
    constructor()
    {
    }
    /**
     * Used to initialize the control instance. Controls can kick off remote server calls and other initialization actions here.
     * Data-set values are not initialized here, use updateView.
     * @param context The entire property bag available to control via Context Object; It contains values as set up by the customizer mapped to property names defined in the manifest, as well as utility functions.
     * @param notifyOutputChanged A callback method to alert the framework that the control has new outputs ready to be retrieved asynchronously.
     * @param state A piece of data that persists in one session for a single user. Can be set at any point in a controls life cycle by calling 'setControlState' in the Mode interface.
     * @param container If a control is marked control-type='standard', it will receive an empty div element within which it can render its content.
     */
    public init(context: ComponentFramework.Context<IInputs>, notifyOutputChanged: () => void, state: ComponentFramework.Dictionary, container:HTMLDivElement): void
    {
        // Add control initialization code
        this.container=container;
        this.context=context;
    }
    /**
     * Called when any value in the property bag has changed. This includes field values, data-sets, global values such as container height and width, offline status, control metadata values such as label, visible, etc.
     * @param context The entire property bag available to control via Context Object; It contains values as set up by the customizer mapped to names defined in the manifest, as well as utility functions
     */
    public updateView(context: ComponentFramework.Context<IInputs>): void
    {
        // Add code to update control view
        this.context=context;
       if(context.mode.isVisible){
           ReactDOM.render(React.createElement(SampleControl),this.container)
       }
    }
    /**
     * It is called by the framework prior to a control receiving new data.
     * @returns an object based on nomenclature defined in manifest, expecting object[s] for property marked as “bound” or “output”
     */
    public getOutputs(): IOutputs
    {
        return {};
    }
    /**
     * Called when the control is to be removed from the DOM tree. Controls should use this call for cleanup.
     * i.e. cancelling any pending remote calls, removing listeners, etc.
     */
    public destroy(): void
    {
        // Add code to cleanup control if necessary
    }
}

Push control to Dataverse

pac pcf push -pp <PUBLISHER PREFIX>

Bind PCF control


Create a new Dummy field (SingleLineOfText) or use any existing unused field.

This image has an empty alt attribute; its file name is image-1.png

Add that field to the main form and by default hide the field.

Bind the control to Dummy Field using classic form editor.

Define ribbon button and action

Add new ribbon button

Call following function on click of this button.
function LaunchPCF(formContext){
    formContext.getControl("k10_dummyfield").setVisible(true);
    setTimeout(function(){
          formContext.getControl("k10_dummyfield").setVisible(false);
    },1000)
}

And that’s it, you Modal will now appear on click of ribbon button.

Summary

  1. Create your PCF control and render only when control is visible.
  2. Do not destroy the control to allow re-render.
  3. Make a dummy field , hide that field by default.
  4. Create a ribbon button and on click of button toggle visibility of the dummy field temporarily.

Dynamics 365 Custom Ribbon Buttons on Dashboard Page Not Showing in UCI

It is observed that custom ribbon buttons don’t show up in unified interface, to solve this issue follow below steps.

Install chrome extension to execute REST calls:

• Open Chrome Webstore
• Look for extension Yet Another Rest Client and add it to your chrome browser.
• Open and login to your Dynamics 365 instance in one of tab
• Open ‘YARC’ extension

• Get organization ID
• Request Type : GET
• Request URL :
https://<CRM ORG>/api/data/v9.1/organizations?$select=organizationid
• Send Request

• From response body note down ‘organization id’

• Update ‘clientfeatureset’
• Request Type : PATCH
• Request URL : https://<CRM ORG>/api/data/v9.1/organizations(<ORGANIZATION ID>)
• Payload:

{'clientfeatureset':'<clientfeatures><clientfeature xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-Instance\"><name>FCB.DashboardCustomizableRibbon</name><value>true</value></clientfeature></clientfeatures>'}

That’s it , your custom buttons will be available now in UCI.

Dynamics 365 UCI Sign-in as different user

With Dynamics CRM UCI Apps , it is now possible to “sign in” as different user. This will be a major benefit to consultants as they troubleshoot issues on behalf of their users.

Why only UCI apps?

The reason this is possible is because most of the data operations in Unified Interface apps are done through the API, and the API supports user impersonation!

How do you do it?

Dynamically add header “CallerObjectId” to all HTTP requests calling dynamics APIs.

  • Get Chrome Extension :
    1. You can user chrome extension your choice but personally i prefer Smart Header as it provide more flexibility in filtering requests.
    2. Enable Extension for incognito mode
      1. Go to chrome://extensions/ find “Smart Header” –> click details –> Check “Allow in incognito” .
  • Configure Smart Header :
    • Click on Smart Header icon and then click configure
    • Create new header and set conditions click save
Request for metadata fails when we add custom header , hence ignoring those calls

  • Access on behalf of user :
    • Get Object Id of user
      • Navigate to user form –> Switch form to “Application User” –> Copy “Azure AD Object Id”.
      • Open a fresh incognito window and set callerobjectid in “Smart Header”.
      • Finally Open CRM UCI app and check user and records for troubleshooting.