Clone Record with Custom Button and Workflow Action in Dynamics 365 CRM

This blog will demonstrate how to build a solution in Microsoft Dynamics 365 CRM where a custom button triggers a workflow action that will clone a record and then open it. I’m writing this blog to be a one-stop shop to help others execute the same set of functionality. I found bits and pieces about this topic over several different websites, and I had to piece the information all together.

The following items will be used to make this happen:

  • Dataverse
  • CE Workflow Action
  • JavaScript Web Resource
  • Dynamics 365 Workflow Tools
  • Ribbon Workbench

Note: There are now 5 different Dynamics 365 apps that serve various CRM needs. In some contexts, you may also see those products referred to as “Customer Engagement” or “CE” apps. Cloning records works the same no matter which of those apps you’re using.

How It Works

The user opens an existing Order and clicks the “Clone Order” custom button at the top of the form. This button is associated to a JavaScript function [Encore.OrderLibrary.cloneOrder], that when triggered, it will call a workflow action [enc_CloneOrder] that will in turn call a 3rd-party plugin [msdyncrmWorkflowTools.CloneRecord] that will clone the record and then open it.

Dynamics-365-Workflow-Tools

This amazing tool has been around for some time and is needed to clone the CRM record. You can download it from here: https://github.com/demianrasko/Dynamics-365-Workflow-Tools

Zip filename.

Ensure you download the managed zip file. Navigate to make.powerapps.com, login, navigate to the desired environment, navigate to solutions, and then import it into your Power Platform system as you would any other solution. You will view it in the list of solutions:

Dynamics 365 Workflow Tools.

This will be needed for our workflow action.

Workflow Action

I suggest creating a solution in your environment to hold all customizations related to the project at hand. Here I created a new solution in which to work:

A screenshot of a Solutions list displaying one entry: Encore - Clone Order. The columns shown are Display name, Name (EncoreCloneOrder), and Created date (12/1/2021), highlighting a Dynamics 365 CE (CRM) Custom Button solution.

Once the solution is created, open it up and create a new workflow action. You do this by selecting the “Switch to classic” option from the top navigation.

A software interface displays the Encore - Clone Order solution with a Dynamics 365 CE (CRM) Custom Button menu on the right, offering Clone, Show dependencies, See history, Apply upgrade (disabled), and Switch to classic options.

It will open the traditional solution window. Select “Processes” in the left navigation and then click “New.”

Screenshot of a Dynamics 365 CE (CRM) interface displaying a menu with options: Information, Components, Entities, Option Sets, Client Extensions, Web Resources, and Processes under Solution: Encore - Clone Order Custom Button.

Ensure “Action” is selected. Provide an appropriate name for the workflow action and select the desired table.

A software interface for creating a new process in Dynamics 365 CE (CRM) Custom Button. The Process name is Clone Order, Category is Action, Entity is Order, and New blank process is selected.

Here I have created a workflow action that is tied to the Order table and have named it Clone Order:

Screenshot of a software interface titled Process: Clone Order in Dynamics 365 CE (CRM) Custom Button. The Information tab is open, showing fields for process name, unique name, and settings for activation and workflow log retention.

You will need the Unique Name of the workflow action – enc_CloneOrder – for the JavaScript Web Resource, so copy it and paste it somewhere for later retrieval.

The JavaScript Web Resource that will be created in the next step will need the new Order GUID; this value is generated when a new Order is created in the Dataverse. Here we create an Output parameter named NewOrderId.

Screenshot of a Dynamics 365 CE (CRM) Custom Button interface showing process arguments. The argument NewOrderId is of type String, optional, and set as output. The right panel displays fields for name, type, entity, required status, direction, and description.

There are only two steps to make this work:

Screenshot of a workflow editor in Dynamics 365 CE (CRM), showing steps: Clone Order with a tool reference, and Assign New Order Id with assigned value NewOrderId. Both steps include Set Properties buttons, ideal for Custom Button automation.

The first step is from the Workflow Tools solution above. When clicking Add Step, the Workflow Tools option will appear; select CloneRecord from the list. Next, click on the Set Properties button when it appears.

For the first value, select Record URL for the related table (Order). Identify any prefix you would like that will be prepended to the name column of the new record. In this case, I added “Cloned – ” to the prefix. If you need to ignore any columns; add the logical name of the column, separated by a semi-colon. In my case, I had to add ordernumber, or an error would occur, referencing a duplicate value.

Screenshot of a software interface showing Set Custom Step Input Properties for a Dynamics 365 CE (CRM) Custom Button. The Cloning Record URL field is required and set to Record URL(Dynamic!OrderId), with Prefix optionally set to Cloned-.

Save and close. Select “Add Step” and then select “Assign Value.” After the new line appears, click “Set Properties.”

D365CE dropdown menu displaying options for steps.

Enter the “Statement Label” and select the Output Parameter you created from “Name.”

To set the “Value,” change “Look for” to the name of your workflow action (Clone Order in this case), and then select “Cloned Guid.”

D365CE-Clone Order, dropdown menu displaying Dynamic Values.

The final result will look something like this:

A software interface displaying a form to assign a new order ID via a Dynamics 365 CE (CRM) Custom Button. The value is set to (Cloned Guid(Clone Order)), and various settings are visible for operators and lookup values.

Save the workflow action and then activate it.

REMEMBER: This workflow action is called by the JavaScript function and will clone the record.

JavaScript Web Resource

I typically manage Web Resources with a Visual Studio web project for my clients. It is a nice way to keep them all in one location, and Visual Studio provides the IntelliSense and formatting when developing JavaScript.

Whether or not Visual Studio is used, create a new JavaScript file, add the below code, and save. We will add the rest of the code later.


if (typeof (Encore) == 'undefined') {
  Encore = {
    __namespace: true
  }
}
if (typeof (Encore.OrderLibrary) == 'undefined') {
  Encore.OrderLibrary = {}
}

Encore.OrderLibrary = (function () {
  var cloneOrder = function (executionContext) {
    
  } // cloneOrder

  return {
    cloneOrder: cloneOrder
  }
} // Encore.OrderLibrary
)()
Screenshot of a code editor displaying JavaScript code for a Dynamics 365 CE (CRM) Custom Button, checking if Encore and Encore.OrderLibrary are undefined, and defining a cloneOrder function inside an immediately invoked function expression.

Navigate to your solution (classic in my case) and create a new Web Resource. From the left navigation, select Web Resources and then select New.

Enter a Name and Display Name; select Script for Type, select Language, and then upload the new JavaScript file you just created. The new Web Resource will look something like this:

Screenshot of a web resource form for OrderLibrary.js in a Dynamics 365 CE (CRM) system, displaying fields for name, display name, type (JScript), language, upload file option, and a URL—ideal for adding a Custom Button.

Navigate to the desired form, open it up, click on Properties, and add the newly added Web Resource.

Screenshot of a forms interface in Dynamics 365 CE (CRM). A Lookup Record window is open, searching for OrderLibrary in the web resource library, with a JavaScript file highlighted for a Custom Button.

It will then show up in the form libraries.

A screenshot of the Form Libraries section in a Dynamics 365 CE (CRM) interface, displaying two listed libraries with options to add, remove, move up, move down, or edit them using a Custom Button.

Since we are not calling this function on load of the form or on edit of any of the columns, we do not need to add any event handlers; we will call the function from the button.

A software interface in Dynamics 365 CE (CRM) Custom Button shows Event Handlers settings, with dropdowns for Control (set to Form) and Event (set to OnLoad). Options include Add, Remove, Up, Down, Edit, Edit Library, and an empty function list below.

Save and close and publish all customizations. Next, navigate to your JavaScript code and add all the following.


if (typeof (Encore) == 'undefined') {
  Encore = {
    __namespace: true
  }
}
if (typeof (Encore.OrderLibrary) == 'undefined') {
  Encore.OrderLibrary = {}
}

Encore.OrderLibrary = (function () {
  var cloneOrder = function (executionContext) {
    console.info("Begin cloneOrder");
    var formContext = null;
    try {
      formContext = executionContext.getFormContext(); // call from home or sub grid
      console.log("Called from Home or Sub Grid");
    }
    catch (e) {
      console.warn("Not being called from Home or Sub Grid");
      try {
        formContext = executionContext;
        console.log("Called from Form");
      }
      catch (e) {
        console.warn("Not being called from Form");
      }
    }

    try {
      if (formContext != null) {
        var entity_id = formContext.data.entity.getId();
        entity_id = StripGUID(entity_id);
        console.log("entity_id: " + entity_id);

        var globalContext = Xrm.Utility.getGlobalContext();
        var serverURL = globalContext.getClientUrl();
        console.log("serverURL: " + serverURL);

        var query = "salesorders(" + entity_id + ")/Microsoft.Dynamics.CRM.enc_CloneOrder";
        console.log("query: " + query);

        var data;

        var req = new XMLHttpRequest();
        req.open("POST", serverURL + "/api/data/v9.1/" + query, true);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.onreadystatechange = function () {
          if (this.readyState == 4 /* complete */) {
            req.onreadystatechange = null;
            if (req.status >= 200 && req.status <= 300) {
              try {
                console.dirxml("this.response: " + this.response);
                data = JSON.parse(this.response);
                console.dirxml("data: " + data);
                console.dirxml("data: " + data.toString());

                var new_order_id = data.NewOrderId;
                console.log("new_order_id: " + new_order_id);

                // OPEN FORM
                var entityFormOptions = {};
                entityFormOptions["entityName"] = "salesorder";
                entityFormOptions["entityId"] = new_order_id;

                Xrm.Navigation.openForm(entityFormOptions);
              }
              catch (e) {
                console.error("error in req.onreadystatechange: " + e);
              }
            } else {
              var error = JSON.parse(this.response).error;
              console.error("error: " + error);
            }
          }
        };
        req.send(window.JSON.stringify(data));
      }
    }
    catch (e) {
      console.error("ERROR - Encore.OrderLibrary.onLoad: " + e);
    }
  } // cloneOrder

  var StripGUID = function (_guid) {
    var rtn = "";
    rtn = _guid.replace("{", "").replace("}", "");
    return rtn;
  } // StripGUID

  return {
    cloneOrder: cloneOrder
  }
} // Encore.OrderLibrary
)()

Explanation of JavaScript Code

Remember, the clicking of the Clone Order button calls the cloneOrder JavaScript function. This function needs to call the enc_CloneOrder custom action that will in turn call the WorkflowTools CloneRecord plugin.

This statement builds the call to the custom action:


var query = "salesorders(" + entity_id + ")/Microsoft.Dynamics.CRM.enc_CloneOrder";  

These lines build the parameters needed to open up the newly created record:


var new_order_id = data.NewOrderId;
var entityFormOptions = {};
entityFormOptions["entityName"] = "salesorder";
entityFormOptions["entityId"] = new_order_id;

And here is the call to open the newly created record:


Xrm.Navigation.openForm(entityFormOptions);

Finally, we will add the custom button to the Order form.

Custom Button

Use the following resource to download, install, and learn the basics of the Ribbon Workbench tool: https://www.develop1.net/public/rwb/ribbonworkbench.aspx

Download and install the Ribbon Workbench solution:

Ribbon workbench zip filename.

Create a new solution that will house only the ribbon customizations. Click Add Existing -> Table, find your table, and do not add any components.

Screenshot of a Solutions table in Dynamics 365 CE (CRM), displaying columns for Display name, Name, and Created. The entry "Encore - Clone Order - Ribbon Workbench" highlights a Custom Button solution added on 12/3/2021.

While in make.powerapps.com, ensure you are in the right environment, click the gear settings icon at the top right and click Advanced Settings:

Settings menu in Power Apps showing options for Admin center, Plan(s), Advanced settings, and easy integration with Dynamics 365 CE (CRM) Custom Button under the Power Apps section.

Click Settings and then Customizations and then click Ribbon Workbench 2016:

Screenshot of a web interface showing a toolbar with options for Settings and Customizations. Below, RIBBON WORKBENCH 2016 is displayed with an icon on the left, highlighting Dynamics 365 CE (CRM) Custom Button features.

Search for your ribbon workbench solution, select it, and then click OK.

A software dialog box displays a selected item, Encore - Clone Order - Ribbon Workbe... with version 1.0.0.1, related to Dynamics 365 CE (CRM) Custom Button features. Below, Order Ribbon Customizations and OrderRibbonCustom... version 1.0 are listed. OK and Cancel buttons are at the bottom.

Once it loads, follow Workbench instructions to add a button.

A toolbar featuring Dynamics 365 CE (CRM) custom buttons labeled NAMICS 365, MARK COMPLETE, SAVE & CLOSE, NEW, and a blue-highlighted CLONE ORDER button. A screenshot showing two button items: new.salesorder.SubmitToWarehouseButton.Button and enc.salesorder.BtnCloneOrder.Button, with the second Dynamics 365 CE (CRM) Custom Button highlighted in yellow.

Add a command:

Text displaying COMMANDS (2) with a dropdown arrow, featuring a Dynamics 365 CE (CRM) Custom Button below—enc.salesorder.cmdCloneOrder.Command, paired with a blue gear icon on the left. A software properties panel for a Dynamics 365 CE (CRM) Custom Button, displaying control details such as ID, command, label, alt text, tooltip, image resources, sequence number, and template alias for a Clone Order button.

Add a custom JavaScript action:

Screenshot of a properties window for a Dynamics 365 CE (CRM) Custom Button showing a command with ID enc.saleorder.cmdCloneOrder.Command, featuring a custom JavaScript action from OrderLibrary.js calling the cloneOrder function using PrimaryControl.

Ensure that you have selected/entered the correct JavaScript file and call the complete function name. For illustration purposes the function name would be something like Encore.OrderLibrary.cloneOrder, assuming you are using namespacing in your JavaScript.

Save and publish all changes.

See It In Action

So what do we have? We created a custom button, that when clicked, will trigger a JavaScript function. That function will call a workflow action that will call a 3rd-party plugin that will clone the record.

Navigate to the desired form and click the “Clone Order” button.

Screenshot of a Dynamics 365 CE (CRM) Custom Button interface displaying a saved order titled Fred Tester Order 0331 B, with options for Save, Save & Close, New, and Clone Order at the top.

Showing the Developer Tools in your browser (F12) will demonstrate the work taking place behind the scenes. Below is a log representing the call to the workflow action:

A code snippet showing a Dynamics 365 CE (CRM) Custom Button triggering the enc_CloneOrder function from OrderLibrary.js to query salesorders with a GUID in Microsoft Dynamics CRM.

After a few seconds, a new Order record will display that is ready for editing and saving:

Screenshot of a business software interface, featuring an order summary. The interface displays Order ID ORD-220325-01323 for the project "Cloned - Fred Tester Order 0331 B," with a green active Order Process bar and a Dynamics 365 CE (CRM) Custom Button.

As mentioned at the start of this blog, I wrote this to illustrate the ability to clone a Dynamics 365 CE record without a ton of effort. There are a few components involved that need to communicate to each other, but all in all, it is a fairly simple solution.

If you’d like to learn more about your Dynamics 365 CE solution, please get in touch with us.

Suggested Articles: