Saturday, January 19, 2013

Dynamics CRM 2011 Open dialog from Javascript

There are many nice things you could do withe dialogs, but making the user to go and choose a dialog from the ribbon isn't really good UI and it doesn't make lot of sense.

Example of when I used the code.
Let say you want to help the user go throw the process of closing case, wouldn't be goo idea to replace the resolve case ribbon button with new ribbon that will open a dialog?

In this example I'm using CrmRestKit, It is required for the code to work, Please make sure you add it to the form.

Javascript:


var DIALOG_NAME = "Test Dialog";

CrmRestKit.ByQuery('Workflow', ['WorkflowId'], "Category/Value eq 1 and StateCode/Value eq 1 and Type/Value eq 1 and Name eq '" + DIALOG_NAME + "'", false)
            .fail(function (t) {
            alert(t)
        })
            .done(function (data, status, xhr) {
            // Assert
            //equals(data.d.results.length, 2, 'Expected two');          
            if (data.d.results.length < 1) {
                alert("Missing dialog named: '"+DIALOG_NAME+"'");
                return;
            }
            var dialogId = data.d.results[0].WorkflowId;
            var objectId = Xrm.Page.data.entity.getId().replace("{", "%7b").replace("}", "%7d");
            var url = Xrm.Page.context.prependOrgName("/cs/dialog/rundialog.aspx?DialogId=%7b" + dialogId + "%7d&EntityName="+ Xrm.Page.data.entity.getEntityName() +"&ObjectId=" + objectId);
            var returnValue = showModalDialog(url);
        });

Sunday, January 6, 2013

Dynamics CRM 2011 - Javascript - Getting selected records from subgrid

Getting the selected values from subgrid in form is not supported, which makes it little bit more tricky.
Lets say you need to get selected records from subgrid after the user got out of the subgrid, like after onchange event of some form attribute. In this case the focus moves out of the subgrid and all you'll get would be an empty list.

The trick to get the selected records is: Get the focus back on the subgrid before trying to get the values.
Anyway it is not supported as well.

My Sample code:

var subgridName = "testSubGrid"

function GetSelectedRecords() {
    var stringOfSelectedIds = "No records were selected";
    if (Xrm.Page.getControl(subgridName) != null) {
        document.getElementById(subgridName).getElementsByTagName('a')[0].focus();
    }
    //document.getElementById(subgridName).control.get_selectedIds()
    if (document.getElementById(subgridName) != null && document.getElementById(subgridName).control != null) {
        selectedRecods = document.getElementById(subgridName).control.get_selectedIds();
        if (selectedRecods != null && selectedRecods.length > 0) {
            stringOfSelectedIds = "Selceted records: " + selectedRecods.join();
        }
        alert(stringOfSelectedIds);
    }
}

GetSelectedRecords()