Sam's Dynamics, Power Platform & AI Blog

Monday, 14 September 2026

Ribbon and Command Bar Customization with JavaScript in Dynamics 365

Everything so far in this series has lived inside the form body — fields, lookups, Web API calls, agent responses. This post moves up one level, to the command bar sitting above all of it: the Save button, the ribbon buttons, the custom "Send for Approval" or "Escalate to Manager" buttons that show up (or don't) depending on the state of the record. That behavior is driven by JavaScript too, and it trips people up in a different way than form scripting does, because the wiring is less obvious.

Two ways to control a button, and why this post is about the JS one

Dynamics 365 gives you two paths to command bar logic. The modern command bar designer lets you write simple Power Fx-style formulas directly against a button's Visible and Enabled properties — no code, no web resource, good enough for straightforward conditions. The classic path — Enable Rules and Display Rules backed by a JavaScript function — is what you reach for when the condition is genuinely complex: multiple entity checks, a Web API call to decide visibility, or logic you want to unit test the same way you'd test any other function in this series.

This post covers the JavaScript path, because that's where the interesting problems are.

Enable Rules vs Display Rules — they are not the same thing

A Display Rule decides whether a button appears at all. A Enable Rule decides whether a button that's already visible can be clicked — a visible-but-greyed-out state. Mixing these up is the single most common ribbon bug: a button that a user can see and click, but that silently does nothing because the actual intent was to hide it until certain conditions were met, not just enable it.

Both rule types point at a JavaScript function with the same signature — Dynamics calls it a CommandChecker function — and both must return a plain boolean.

function canSendForApproval(primaryControl) {
  var formContext = primaryControl;
    var status = formContext.getAttribute("statuscode").getValue();
      var isDirty = formContext.data.getIsDirty();
      
        // only show/enable once saved and still in Draft
          return status === 1 && !isDirty;
          }

Notice the parameter isn't literally "the form" — it's whatever you configured as a CRM Parameter when you wired the rule up in the Ribbon Workbench (or classic solution ribbon editor). PrimaryControl is the one you'll use constantly, because it gives you the same formContext-shaped object you already know from every other post in this series — getAttribute, getValue, ui, all of it.

A realistic enable rule: role- and state-aware

Real conditions are rarely just one field check. Here's a button that should only be enabled for the record owner, only once the opportunity has reached the Propose stage, and only if there's no pending approval already:

async function canEscalate(primaryControl) {
  var formContext = primaryControl;
    var userId = Xrm.Utility.getGlobalContext().userSettings.userId;
      var ownerId = formContext.getAttribute("ownerid").getValue();
      
        if (!ownerId || ownerId[0].id.toLowerCase() !== userId.toLowerCase()) {
            return false;
              }
              
                var recordId = formContext.data.entity.getId().replace(/[{}]/g, "");
                  var result = await Xrm.WebApi.retrieveRecord(
                      "opportunity", recordId, "?$select=salesstage,con_hasopenescalation"
                        );
                        
                          return result.salesstage === 2 && !result.con_hasopenescalation;
                          }

CommandChecker functions can be async — Dynamics will wait for the promise before deciding the button's state. Just be aware that every extra Web API call in a rule adds latency to ribbon rendering, especially on grids with dozens of visible rows each re-evaluating their own rule. Keep the check as cheap as you can; if you find yourself calling the Web API from an enable rule on a subgrid, it's often faster to precompute that value onto the record itself (a rollup field or a plugin-set field) and check it directly, rather than querying live from the ribbon.

What actually happens on click

The rule only controls visibility and enablement — a separate function, wired up as the button's Action, is what runs when someone actually clicks it:

async function escalateToManager(primaryControl) {
  var formContext = primaryControl;
    var confirm = await Xrm.Navigation.openConfirmDialog({
        title: "Escalate this opportunity?",
            text: "Your manager will be notified and the record flagged for review.",
              });
              
                if (!confirm.confirmed) return;
                
                  await formContext.data.save();
                    await Xrm.WebApi.updateRecord(
                        "opportunity",
                            formContext.data.entity.getId().replace(/[{}]/g, ""),
                                { con_hasopenescalation: true }
                                  );
                                  
                                    formContext.ui.refreshRibbon();
                                    }

That last line matters more than it looks. Ribbon state doesn't automatically re-evaluate just because you changed a value in code — Dynamics re-checks your rules on load, on save, and on a few built-in events, but not every time an attribute changes. If your action changes something an enable rule depends on, call formContext.ui.refreshRibbon() yourself, or the button will sit in its old state until the user manually refreshes the page.

Where the JavaScript actually lives

Same rule as every other post in this series: the function has to be in a web resource that's part of your solution, and the Ribbon Workbench (or the classic ribbon customization) references it by $webresource: path plus function name — not by file path alone. A function that works perfectly when you test it in the console but does nothing on the actual button almost always means one of three things: the web resource reference in the ribbon XML is wrong, the function isn't actually included in that web resource, or you edited the JS but forgot to publish afterward — the same publish-and-cache trap from the ALM post shows up here too.

Testing rules without clicking through the UI fifty times

Because CommandChecker functions take a plain object shaped like formContext and return a boolean, they're some of the easiest ribbon-adjacent code to unit test — you don't need a real form, just an object with the methods your function actually calls:

test("escalate disabled when not the owner", async () => {
  const fakeForm = {
      getAttribute: () => ({ getValue: () => [{ id: "other-user-guid" }] }),
        };
          expect(await canEscalate(fakeForm)).toBe(false);
          });

This is the same pattern from the testing and debugging post — mock the pieces of formContext your function actually touches, and you can validate ribbon logic in milliseconds instead of navigating to a record, checking a button state, changing data, and reloading, over and over.

A short checklist before you ship a ribbon change

Did you use a Display Rule where you meant "hide it" and an Enable Rule where you meant "show it but grey it out" — not the other way around? Is any Web API call inside an enable rule cheap enough to run on every grid row, not just a form? Does your click-handler call refreshRibbon() if it changes something another rule depends on? And is the web resource holding these functions actually included in the solution you're about to export — the same ALM discipline from a couple of posts back applies just as much to ribbon code as it does to form scripts.

Next up

We've covered forms, data, agents, testing, deployment, and now the command bar. Next in the series: Business Process Flow JavaScript — reading and moving the active stage in code, and the specific quirks of scripting against a BPF versus a regular form.

No comments:

Post a Comment

Packaging and Deploying Web Resources: A Practical ALM Workflow for Dynamics 365 JavaScript

You've written the script. You've unit-tested the logic and stepped through it in dev tools. It works perfectly on your form. Now co...