28/05/2019

How to add a button in D365 using Ribbon Workbench

We are going to add/create a custom button on an entity in D365 using ribbon workbench solution.

Scenario: On click of a button, we are going to generate a GUID and update that value in a field.

Prerequisites:

1. Ribbon Workbench solution (can be downloaded from the above URL)
2. Create a custom entity (in this post, we have created an entity called "Requests")
3. Create a solution and add the above entity to it
4. Create a web resource (JScript) to generate a GUID

How To?

1. Log into D365, Go to SETTINGS -> Solutions -> Click on "RIBBON WORKBENCH 2016"
2. Select a solution from the available list ("My Solution" in our post)
3. Select the BUTTON on the left side ribbon. Drag and place it on the Main Form as shown in the below image
4. Click on the + button next to COMMANDS(1) as shown below and change the Id to "new.new_request.generatekey.Command". Changing the Id value is not mandatory, its just for our convenience

a. Now click on "+ Add Action" and select "JavaScript Action"
b. Select respective Web Resource from the "Library" lookup and add the function name in "Function Name" field
Eg: Library:              $webresource:new_uniqueid.js
       Function Name: buttonGenerateKey

Click on "Add Parameter" and select "CRM Parameter". Choose "PrimaryControl" from the drop-down.



Note: This parameter helps us to get execution context on on button click

5. Now click on on the BUTTONS(1) and select the above command that we have created. Update the button labels and other fields as shown in the below image

6. Publish all the changes
7. Go to Requests entity and click on New and fill the required data. Click on "Generate Key" button. There we go, an unique key which is generated is updated in the field


Here is the sample code that's used in the post


function buttonGenerateKey(primaryControl)
{
    var formContext = primaryControl;
    var uniqueNumber = this.generateUniqueKey();
    if (uniqueNumber != null)
    {
        formContext.getAttribute("new_requestkey").setValue(uniqueNumber);
    }
    else return;
};
function generateUniqueKey()
{
    var d = new Date().getTime();
    if (Date.now)
    {
            d = Date.now();
    }
    var uniqueID = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c)
    {
            var r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uniqueID;
}