Wednesday, July 29, 2015

Set CRM IFrame Url Dynamically to aspx page / Post data to CRM IFrame aspx page / Get Response from aspx page in CRM IFrame – CRM 2015 / CRM 2013/ 2011


Set CRM IFrame Url Dynamically to aspx page / Post data to CRM IFrame aspx page / Get Response from aspx page in CRM IFrame – CRM 2015 / CRM 2013/ 2011

 

CRM Js

// In following example on page load am binding iframe url dynamically and calling aspx page. On save, posting data to aspx page to perform some operation. On success am saving crm from data.

var dbWaiting;
 function onLoad() {
    dbWaiting = true;

    // Set IFrame URL dynamically to aspx page / service.
    var databaseRecordIDField = Xrm.Page.getAttribute('sa_databaserecordid');
    var o = document.getElementById('IFRAME_TemplateBody');

    if (o != null) {
        o.src = 'https://server.com/emailclient/template?id=' + databaseRecordIDField.getValue();
    }
    if (o != null) {
        IFrame.setSrc(o.src);
    }
    else {
        var IFrame = Xrm.Page.ui.controls.get("IFRAME_TemplateBody");
        IFrame.setSrc('https://server.com/emailclient/template?id=' + databaseRecordIDField.getValue());
    }

    // Add event listener to get response back from aspx page / service
    if (window.addEventListner) {
        window.parent.addEventListener("message", receiveMessage, false);
        window.addEventListener("message", receiveMessage, false);

    }
    else if (window.attachEvent) {
        window.parent.attachEvent("onmessage", receiveMessage);
        window.attachEvent("onmessage", receiveMessage);
    }
}

 

function onSave(ExecutionObj) {
    if (dbWaiting == true) {
        ExecutionObj.getEventArgs().preventDefault();
        var databaseRecordIDField = Xrm.Page.getAttribute('sa_databaserecordid');
        var o = document.getElementById('IFRAME_TemplateBody');

        // Data/ Json object to pass to aspx page/ service
        var pass_data = {
            'name': Xrm.Page.getAttribute('sa_name').getValue(),
            'id': Xrm.Page.getAttribute('sa_databaserecordid').getValue(),
            'action': 'saveRequestedFromCRM',
        };

         // Post data to aspx page/ service, you will get response back in receiveMessage
        if (o != null) {
            o.contentWindow.postMessage(JSON.stringify(pass_data), 'https://server.com/emailclient/template?id=' + databaseRecordIDField.getValue());
        }
        else {
            Xrm.Page.ui.controls.get("IFRAME_TemplateBody").getObject().contentWindow.postMessage(JSON.stringify(pass_data), 'https://server.com/emailclient/template?id=' + databaseRecordIDField.getValue());
        }
    }
}

 

function receiveMessage(event) {
    dbWaiting = false;
    if (event.data === 'error') {
        alert('An error occurred, could not save.  Please make sure the {{Body}} tag is included. ');
    }
    else {
        // You can read response object in to event.data
        Xrm.Page.data.entity.save();
    }
}

No comments: