Firing workflows against multiple records from a ribbon button


UPDATE (2013-04-25):

I recently ran into a problem with this code. When running against large numbers of records (200+) the URL can become very long. This can lead to a number of issues…

1) IIS can hit configured URL length limits causing 500 errors to appear within CRM dialogs. These can be changed in IIS Manager – Request Filtering, Edit Feature Settings.

iis_config3_zoom75

2) I use IE9. Even though the popup blocker was disabled, a dialog would appear saying “A Microsoft Dynamics CRM window was unable to open, and may have been blocked by a pop-up blocker…”. To resolve this, I removed line 21 in my launchWorkflowMulti function. Turns out you don’t have to specify the list of IDs twice (or you no longer have to in current rollups).

Screenshot---25_04_2013-,-18_06_09


I wanted to be able to allow users to “authorise” a set of records from the homepage grid. In this case, authorising a record simply meant executing a particular workflow against it.

The functionality needed to be similar to the standard “Run Workflow” button – with a modal progress bar but without having to select which workflow to run first. Critically the user needed to be able to select any number of records to be authorised in one operation.

Here’s how I got it working…

Configure Ribbon Buttons

Configure your ribbon in the usual way. Or you can give this a try – CRM 2011 Visual Ribbon Editor (http://crmvisualribbonedit.codeplex.com/).

<RibbonDiffXml>
  <CustomActions>
    <CustomAction Id="Mscrm.HomepageGrid.new_casesummary.MainTab.Workflow.Controls.Approve" Location="Mscrm.HomepageGrid.new_casesummary.MainTab.Workflow.Controls._children" Sequence="99">
      <CommandUIDefinition>
        <Button Id="Mscrm.HomepageGrid.new_casesummary.MainTab.Workflow.Controls.Approve.Button" Command="Mscrm.HomepageGrid.new_casesummary.Approve.Command" LabelText="Approve Summary" ToolTipTitle="Approve Case Summary" ToolTipDescription="Run approval procedure for the current Case Summary" TemplateAlias="o1" Image16by16="$webresource:new_icon_thumbsup_16" Image32by32="$webresource:new_icon_thumbsup_32" />
      </CommandUIDefinition>
    </CustomAction>
    <CustomAction Id="Mscrm.HomepageGrid.new_casesummary.MainTab.Workflow.Controls.Authorise" Location="Mscrm.HomepageGrid.new_casesummary.MainTab.Workflow.Controls._children" Sequence="100">
      <CommandUIDefinition>
        <Button Id="Mscrm.HomepageGrid.new_casesummary.MainTab.Workflow.Controls.Authorise.Button" Command="Mscrm.HomepageGrid.new_casesummary.Authorise.Command" LabelText="Authorise Summary" ToolTipTitle="Authorise Case Summary" ToolTipDescription="Run authorisation procedure for the current Case Summary" TemplateAlias="o1" Image16by16="$webresource:new_icon_thumbsup_16" Image32by32="$webresource:new_icon_thumbsup_32" />
      </CommandUIDefinition>
    </CustomAction>
  </CustomActions>
  <CommandDefinitions>
    <CommandDefinition Id="Mscrm.HomepageGrid.new_casesummary.Approve.Command">
      <EnableRules></EnableRules>
      <DisplayRules></DisplayRules>
      <Actions>
        <JavaScriptFunction Library="$webresource:new_script_ribbonHandler" FunctionName="launchWorkflowMulti">
          <StringParameter Value="Are you sure you want to approve the selected records?" />
          <StringParameter Value="E4D7011F-A05F-4676-8630-56D93D89B2C7" />
          <CrmParameter Value="SelectedControlSelectedItemIds" />
          <BoolParameter Value="true" />
          <CrmParameter Value="SelectedEntityTypeCode" />
        </JavaScriptFunction>
      </Actions>
    </CommandDefinition>
  </CommandDefinitions>
</RibbonDiffXml>

So, when clicked, the button fires the function launchWorkflowMulti method within my new_script_ribbonHandler script.

The function’s parameters are:-

  • Confirmation Message – Message to prompt() the user with before continuing
  • GUID – The GUID of the workflow we want to run
  • SelectedControlSelectedItemIds – CRM substitutes this parameter with the list of currently selected records from the grid
  • True/False – This boolean parameter dictates if the screen will be refreshed after the procedure is complete.
  • SelectedEntityTypeCode – CRM substitutes this parameter with the Object Type Code for the current entity

For some reason you have to provide the list of GUIDs both as part of the URL and as an array to the arguments parameter of the built-in openStdDlg() function.

Finally, here’s the function itself:-

function launchWorkflowMulti(confirmMessage, workflowId, recordIds, reload, objectTypeCode) {
  
  // Check variables
  if (objectTypeCode == "") {return;}
  if (recordIds == "") {return;}
  
  // Show confirmation to user
  if (confirmMessage != "") {
    if (!confirm(confirmMessage)) {return;}
  }
  
  // Split recordID list into array (on comma)
  var aRecords = (recordIds + "").split(",");
  if (aRecords.length == 0) {return;}
  
  // Open dialog
  var url = prependOrgName("/_grid/cmds/dlg_runworkflow.aspx")
    + "?iObjType=" + CrmEncodeDecode.CrmUrlEncode(objectTypeCode)
    + "&amp;iTotal=" + CrmEncodeDecode.CrmUrlEncode(aRecords.length)
    + "&amp;wfId=" + CrmEncodeDecode.CrmUrlEncode("{" + workflowId + "}") + ""
    + "&amp;sIds=" + CrmEncodeDecode.CrmUrlEncode(recordIds);
  
  var oresult = openStdDlg(url, aRecords, 500, 200);
  
  if (reload) {window.location.reload(true);}
  
}
Advertisements

CRM Form message / response / error / warning area

I had a requirement to show a warning message to users but didn’t want to use a basic Alert popup. I decided to write a function which inserts a div into the form with various pre-defined options for severity of the message. It uses existing CRM images so no need to create any Web Resources.

Here’s how it looks in the context of a page:

Previews of the colour schemes:

“ok” or “success”


“info” or “information”


“warn” or “warning”


default

Here’s the code:

function ShowWarning(message, mode) {

var boxId = "warning";    // DOM ID of new DIV

if (document.getElementById(boxId)) {
document.getElementById("crmFormTabContainer").removeChild(document.getElementById(boxId));
}

if (!message || message=="") {return;}

var warning = document.createElement("DIV");
warning.style.padding = "10px 10px 10px 50px";
warning.style.border = "1px solid";
warning.style.height = "50px";
warning.style.display = "table-cell";
warning.style.verticalAlign = "middle";
warning.style.margin = "15px 15px 5px 15px";

var colour = "";

switch (mode) {

case "information":
case "info":
warning.style.background = "#BDE5F8 url('/_imgs/error/notif_icn_info.png') 10px 55% no-repeat";
warning.style.borderColor = "#00529B";
colour = "#00529B";
break;

case "success":
case "ok":
warning.style.background = "#DFF2BF url('/_imgs/importwizard_greentick.gif') 20px 55% no-repeat";
warning.style.borderColor = "#4F8A10";
colour = "#4F8A10";
break;

case "warning":
case "warn":
warning.style.background = "#FEEFB3 url('/_imgs/error/notif_icn_warn.png') 10px 55% no-repeat";
warning.style.borderColor = "#9F6000";
colour = "#9F6000";
break;

default:
warning.style.background = "#FFBABA url('/_imgs/error/notif_icn_critical.png') 10px 55% no-repeat";
warning.style.borderColor = "#D8000C";
colour = "#D8000C";
break;

}

warning.innerHTML = "<table cellpadding=0 cellspacing=0 border=0 width=100% height=100%><tr><td valign=middle style=\"font-size: 13px; color: " + colour + ";\">" + message + "</td></tr></table>";

document.getElementById("crmFormTabContainer").insertBefore(warning, document.getElementById("crmFormTabContainer").firstChild);

}

Ended up using a table to ensure the vertical alignment. Any CSS trick I tried didn’t want to play in IE.

To call the function, use something like this:

ShowWarning("You clicked the wrong button!!!", "warn");

Message – The message you want to display
Mode – The severity (“ok”, “warn”, “info”) you want to use (optional). Any non-recognised mode will be treated as an error (red).

Preview entity data in an iFrame (CRM 2011)

We wanted to be able to display a bunch of useful information when a user selected a record from a lookup. I wanted to use as much native CRM stuff as possible so non-developers in the team could change what fields are displayed and where without having to modify any code. I think it turned out pretty cool. Hope some people find it useful.

The result

In the screenshot, the relevant bit is under the “Op Site Data” heading. When a user selects an “Op Site”, the tab pops open and the grey box is displayed showing related data for that record.

So how is it done ?

IFrame

Add a new tab and iFrame to the relevant form. Set the URL of the iFrame to “about:blank”.
Make sure you un-tick “Restrict cross-frame scripting”.

Attach a JavaScript function to the onReadyStateChange event of the iFrame. In this case, I’ve called it iframe_onload.

Related Entity Form

You need to add a new form to the related entity. In this case it’s a custom entity called Op Site. It doesn’t matter what name you give it – I called it “Preview”.

Set the new form up to only display the fields you want. I found it best to use a three column layout.

Print Preview

Now here’s the science bit. Go and look at the new form you created and do a Print Preview. This will bring up a read-only version of the form – this is the basis of what we’ll display in the iFrame. Copy the URL of the preview to the clipboard.

We’ll have to get rid of those Print and Close toolbar buttons and the space-wasting headings and whitespace.

New form in print preview mode

JavaScript

NB This stuff requires jQuery. I was using v1.6.2.

There are two functions to perform this preview. The first handles the opening / closing of the tab and sets the URL for the iFrame. The second cleans up the content of the iFrame so it takes up less room.

First Function

I called this function ShowOpSiteData. It needs to be attached to the Form onLoad event as well as the Field’s onChange event (in this case the field is called Op Site). You will need the URL of the print preview page that you copied earlier.

function ShowOpSiteData() {

  // Collapse the preview tab
  var elTab = Xrm.Page.ui.tabs.get("tab_4");
  elTab.setDisplayState("collapsed");

  // Get the value (GUID) of the selected lookup
  var opSite = Xrm.Page.getAttribute("hpd_opsiteid").getValue();
  if (!opSite) { return; }
  var opSiteId = opSite[0].id;
  if (opSiteId == "") {return;}

  // Set the iFrame URL to the print preview URL.
  // Insert the GUID into the URL.
  if (opSiteId != "") {
    var el = document.getElementById("IFRAME_opsitedata");
    var el2 = document.getElementById("printArea");
    var url = "/_forms/print/print.aspx?allsubgridspages=false&amp;formid=69144f31-713b-4eeb-9d89-096d893be6a2&amp;id=" + escape(opSiteId) + "&amp;objectType=10004";
    el.src = url;
  }

}

Second Function

I called this function iframe_onLoad (originally I had it attached (via code) to the iFrame’s onLoad event). The function needs to be attached to the iFrame’s onReadyStateChange event. This function is where the jQuery comes in – mainly for the Sizzle selector system.

The function basically goes into the iFrame and removes the toolbar, the headings and the big whitespaces. See the comments for full details.

function iframe_onLoad() {

  // Grab the iFrame element.
  // Check it's fully loaded and we have the page is correct.
  var iFrame = document.getElementById("IFRAME_opsitedata");
  if (iFrame.readyState != "complete") {return;}
  if (iFrame.src.indexOf("/_forms/print/print.aspx") == -1) {return;}

  // Grab the preview iFrame as a jQuery object. Remove the toolbar.
  var IF1 = jQuery("#IFRAME_opsitedata");
  IF1.contents().find("tr#printHeader").remove();

  // Grab the sub-iFrame within the preview iFrame.
  var IF2 = IF1.contents().find("iframe#printMain");
  // Remove the big header and icon
  IF2.contents().find("tr.ms-crm-Form-HeaderContainer").remove();
  // Remove the big whitespace at the top
  IF2.contents().find("div.ms-crm-Tab-Print").first().remove();
  // Remove a bunch of whitespace around the second iFrame
  IF2.contents().find("td.ms-crm-Form-Page-Main-cell").css("padding","0px");
  // Reinstate the whitespace next to the scrollbar
  IF2.contents().find("td.ms-crm-Form-Page-Main-cell").css("padding-right","8px");
  // Remove the big whitespace at the bottom
  IF2.contents().find("td.ms-crm-Form-Footer").parent().remove();

  // Remove the header text. The text isn't within any specific tag so just performing a replace.
  // The only part of the code that isn't directly re-usable
  IF2.contents().find("div.ms-crm-Tab-Print").each(function() {
    jQuery(this).html( jQuery(this).html().replace("General","") );
    jQuery(this).html( jQuery(this).html().replace("Response Information","") );
    jQuery(this).html( jQuery(this).html().replace("Notes","") );
  });

  // Expand Op Site Data tab, revealing the fully rendered preview
  var elTab = Xrm.Page.ui.tabs.get("tab_4");
  elTab.setDisplayState("expanded");

}

Success

That’s it! Feel free to leave a comment if you found this useful, spot a problem or have a question.

Triggering a Workflow from a Ribbon Button

Add Button to Entity Ribbon

Export the entity in question and open up customizations.xml. Add the following within the CustomActions tag…

<CustomAction
  Id="CA_MyFirstButton"
  Location="Mscrm.Form.account.MainTab.Save.Controls._children"
  Sequence="31">
  <CommandUIDefinition>
    <Button
      Id="B_MyFirstButton"
      Command="Mscrm.RunSomeJS"
      LabelText="Button Label"
      ToolTipTitle="Run Test Workflow"
      ToolTipDescription="Runs the test workflow to see if this works"
      TemplateAlias="o1"
      Image16by16="/_imgs/ribbon/tools_16.png"
      Image32by32="/_imgs/ribbon/tools_32.png" />
  </CommandUIDefinition>
</CustomAction>

Location sets which area of the ribbon the button will appear on.
Sequence sets where within that ribbon it will appear.
LabelText sets the text which appears under the icon on the ribbon.
TemplateAlias (who knows!)

Create the click action

Now we need to add the command Mscrm.RunSomeJS within the CommandDefinitions section.

<CommandDefinition
  Id="Mscrm.RunSomeJS">
  <EnableRules>
    <EnableRule Id="Mscrm.Enabled" />
  </EnableRules>
  <DisplayRules>
    <DisplayRule Id="Mscrm.CanWriteAccount" />
  </DisplayRules>
  <Actions>
    <JavaScriptFunction
      FunctionName="TriggerWorkflow"
      Library="$Webresource:isah_test">
      <StringParameter
        Value="{guid of account entity}" />
      <StringParameter
        Value="{7D78531A-23EB-4042-9626-1D80DFC10A8D}" />
    </JavaScriptFunction>
  </Actions>
</CommandDefinition>

EnableRules sets if the button is greyed out on the toolbar (always enabled in this example)
DisplayRules sets if the button appears on the toolbar (if the user can write to the account entity in this example)
FunctionName sets the name of the function to run within the web resource
Library sets the name of the web resource JavaScript library to access
StringParameters
in this case are the guid of the account entity (not used currently) and the guid of the workflow to trigger

JavaScript to Fire the Workflow

function TriggerWorkflow(entityName,workflowGuid) {

  var xx = prompt(Xrm.Page.data.entity.getId(),Xrm.Page.data.entity.getId());

  /*Generate Soap Body.*/
  var soapBody = "<soap:Body>" +
                 "  <Execute xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
                 "    <Request xsi:type=\'ExecuteWorkflowRequest\'>" +
                 "      <EntityId>" + Xrm.Page.data.entity.getId() + "</EntityId>" +
                 "      <WorkflowId>" + workflowGuid + "</WorkflowId>" +
                 "    </Request>" +
                 "  </Execute>" +
                 "</soap:Body>";

  /*Wrap the Soap Body in a soap:Envelope.*/
  var soapXml = "<soap:Envelope " +
                "  xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' " +
                "  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " +
                "  xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
                GenerateAuthenticationHeader() +
                soapBody +
                "</soap:Envelope>";

  /* Create the XMLHTTP object for the execute method.*/
  var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  xmlhttp.open("POST", "/MSCRMservices/2007/crmservice.asmx", false);
  xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
  xmlhttp.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Execute");

  /* Send the XMLHTTP object. */
  xmlhttp.send(soapXml);

}