Pages

Monday, October 15, 2012

Ribbon: Get View ID (Context Sensitive)

Let's say you want to execute an action that will act on the view that is currently being viewed i.e. the objective is that the action will be context sensitive to the current view. How can this be achieved?

The first thing to do is of course to add the a button to the application ribbon and you'd be well advised to use the Ribbon Workbench Tool to do this. As we are adding a button that will appear in the grid views you'll need to be sure to select the HomePage option.


As illustrated in the screenshot above, the action for the ribbon button references a JavaScript function, so you will of course need to create a JScript web resource and a custom function to match what you define for the ribbon action command.

The JScript function will then take care of launching the custom action and passing in the View ID of the view currently being viewed - which is the crux of this post. The script below provides the method for obtaining the view ID:

function GetViewID() {
    try {
        if (document.getElementById('crmGrid_SavedNewQuerySelector')) {
            var view = document.getElementById('crmGrid_SavedNewQuerySelector');

            var firstChild = view.firstChild;

            var currentview = firstChild.currentview;
            if (currentview) {
                var viewId = currentview.valueOf();
    alert(viewId);
            }
        }
        else {
            alert("No Element");
        }
    }
    catch (e) {
        alert(e.message);
    }
}

The result of the above exercise will be a button on the ribbon that when clicked will pop up with the ID of the current view:


You can of course tailor this jscript to pass in the retrieved View ID to whatever custom action you wish to execute.

3 comments:

  1. Unfortunately I get back "javascript:;" for the variable "view" when I try to run this code.

    ReplyDelete
  2. firstChild.currentview didn't work for me, I had to replace it with firstChild.getAttribute(“currentview”).

    ReplyDelete